java代码中直接问号加参数请求其他接口

傷城~ 2022-06-07 08:38 172阅读 0赞
  1. /**
  2. * 程序中访问http数据接口
  3. */
  4. public static String getURLContent(String urlStr) {
  5. /** 网络的url地址 */
  6. URL url = null;
  7. /** http连接 */
  8. HttpURLConnection httpConn = null;
  9. /**//** 输入流 */
  10. BufferedReader in = null;
  11. StringBuffer sb = new StringBuffer();
  12. try{
  13. url = new URL(urlStr);
  14. in = new BufferedReader( new InputStreamReader(url.openStream(),"UTF-8") );
  15. String str = null;
  16. while((str = in.readLine()) != null) {
  17. sb.append( str );
  18. }
  19. } catch (Exception ex) {
  20. } finally{
  21. try{
  22. if(in!=null) {
  23. in.close();
  24. }
  25. }catch(IOException ex) {
  26. }
  27. }
  28. String result =sb.toString();
  29. System.out.println(result);
  30. return result;
  31. }
  32. **
  33. * post方式请求http服务
  34. * @param urlStr
  35. * @param params name=yxd&age=25
  36. * @return
  37. * @throws Exception
  38. */
  39. public static String getURLByPost(String urlStr,String params)throws Exception{
  40. URL url=new URL(urlStr);
  41. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  42. conn.setRequestMethod("POST");
  43. conn.setDoOutput(true);
  44. conn.setDoInput(true);
  45. PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
  46. printWriter.write(params);
  47. printWriter.flush();
  48. BufferedReader in = null;
  49. StringBuilder sb = new StringBuilder();
  50. try{
  51. in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8") );
  52. String str = null;
  53. while((str = in.readLine()) != null) {
  54. sb.append( str );
  55. }
  56. } catch (Exception ex) {
  57. throw ex;
  58. } finally{
  59. try{
  60. conn.disconnect();
  61. if(in!=null){
  62. in.close();
  63. }
  64. if(printWriter!=null){
  65. printWriter.close();
  66. }
  67. }catch(IOException ex) {
  68. throw ex;
  69. }
  70. }
  71. return sb.toString();
  72. }
  73. 本文转载,原文地址http://blog.csdn.net/xiaobaoxiaodun/article/details/6881243

如果任何疑问或学习交流,请搜索公众号”老秦的快乐生活”获取我的联系方式

发表评论

表情:
评论列表 (有 0 条评论,172人围观)

还没有评论,来说两句吧...

相关阅读