通过HttpURLConnection发送GET和POST请求(解决转义码问题)

╰+攻爆jí腚メ 2023-03-13 06:42 28阅读 0赞

通过HttpURLConnection发送GET和POST请求

  1. public class HttpURLConnectionDemo {
  2. /**
  3. * get
  4. * @param httpUrl 请求
  5. * @param encode 编码
  6. * @return
  7. */
  8. public static String deGet(String httpUrl,String encode){
  9. if(encode == "" || encode == null){
  10. //设置默认编码
  11. encode = "utf-8";
  12. }
  13. HttpURLConnection conn = null;
  14. InputStream is = null;
  15. BufferedReader br = null;
  16. StringBuilder result = new StringBuilder();
  17. try{
  18. //创建远程url连接对象
  19. URL url = new URL(httpUrl);
  20. //通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
  21. conn = (HttpURLConnection) url.openConnection();
  22. conn.setRequestMethod("GET");
  23. //设置连接超时时间和读取超时时间
  24. conn.setConnectTimeout(15000);
  25. conn.setReadTimeout(60000);
  26. conn.setRequestProperty("Accept", "application/json");
  27. //发送请求
  28. conn.connect();
  29. //通过conn取得输入流,并使用Reader读取
  30. if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
  31. is = conn.getInputStream();
  32. br = new BufferedReader(new InputStreamReader(is, encode));
  33. String line;
  34. while ((line = br.readLine()) != null){
  35. result.append(line);
  36. System.out.println(line);
  37. }
  38. }else{
  39. System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
  40. }
  41. }catch (MalformedURLException e){
  42. e.printStackTrace();
  43. }catch (IOException e){
  44. e.printStackTrace();
  45. }catch (Exception e){
  46. e.printStackTrace();
  47. }finally {
  48. try{
  49. if(br != null){
  50. br.close();
  51. }
  52. if(is != null){
  53. is.close();
  54. }
  55. }catch (IOException ioe){
  56. ioe.printStackTrace();
  57. }
  58. conn.disconnect();
  59. }
  60. return result.toString();
  61. }
  62. /**
  63. * post
  64. * @param httpUrl 请求
  65. * @param encode 编码
  66. * @return
  67. */
  68. public static String doPost(String httpUrl,String encode){
  69. if(encode == "" || encode == null){
  70. //设置默认编码
  71. encode = "utf-8";
  72. }
  73. OutputStreamWriter out = null;
  74. BufferedReader in = null;
  75. StringBuilder result = new StringBuilder();
  76. HttpURLConnection conn = null;
  77. try{
  78. URL url = new URL(httpUrl);
  79. conn = (HttpURLConnection) url.openConnection();
  80. conn.setRequestMethod("POST");
  81. //发送POST请求必须设置为true
  82. conn.setDoOutput(true);
  83. conn.setDoInput(true);
  84. //设置连接超时时间和读取超时时间
  85. conn.setConnectTimeout(30000);
  86. conn.setReadTimeout(10000);
  87. conn.setRequestProperty("Content-Type", "application/json");
  88. conn.setRequestProperty("Accept", "application/json");
  89. //获取输出流
  90. out = new OutputStreamWriter(conn.getOutputStream());
  91. String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
  92. out.write(jsonStr);
  93. out.flush();
  94. out.close();
  95. //取得输入流,并使用Reader读取
  96. if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
  97. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode));
  98. String line;
  99. while ((line = in.readLine()) != null){
  100. result.append(line);
  101. System.out.println(line);
  102. }
  103. }else{
  104. System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
  105. }
  106. }catch (Exception e){
  107. e.printStackTrace();
  108. }finally {
  109. try{
  110. if(out != null){
  111. out.close();
  112. }
  113. if(in != null){
  114. in.close();
  115. }
  116. }catch (IOException ioe){
  117. ioe.printStackTrace();
  118. }
  119. }
  120. return result.toString();
  121. }
  122. public static void main(String[] args) {
  123. String url = "http://57.145.140.145:7776/tyc/getTycInfo?params=%7B%22id%22:%22%22,%22name%22:%22%E5%9B%9B%E5%B7%9D%E5%B7%9D%E5%A4%A7%E6%99%BA%E8%83%9C%E7%B3%BB%E7%BB%9F%E9%9B%86%E6%88%90%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%7D&url=http:%2F%2Fopen.api.tianyancha.com%2Fservices%2Fv4%2Fopen%2Fpast%2Fic";
  124. System.out.println(deGet(url,""));
  125. }
  126. }

关于转义码问题

发现如果是浏览器拷贝过来字符通过了
String url = “http://57.145.140.145:7776/tyc/getTycInfo?params=%7B%22id%22:%22%22,%22name%22:%22%E5%9B%9B%E5%B7%9D%E5%B7%9D%E5%A4%A7%E6%99%BA%E8%83%9C%E7%B3%BB%E7%BB%9F%E9%9B%86%E6%88%90%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%7D&url=http:%2F%2Fopen.api.tianyancha.com%2Fservices%2Fv4%2Fopen%2Fpast%2Fic”;
而没有转义符的会出现400错误

原因是编码问题

文件格式可能不是utf-8,我们可以把参数在统一转码一下。

  1. String url2 = null;
  2. try {
  3. url2 = "http://58.130.66.120/gzeimm_web/capDec2/getEnpFillInfo.rpcc?parameter=" +
  4. URLEncoder.encode("{\"date\":\"2020-05-11\"}", "UTF-8");
  5. } catch (UnsupportedEncodingException e) {
  6. e.printStackTrace();
  7. }
  8. String url3= "http://58.130.66.120/gzeimm_web/capDec2/getEnpFillInfo.rpcc?parameter={%22date%22:%222020-05-11%22}%22";

上面两个请求是正常滴。
建议在方法中对参数转码

关于参数建议

参数我们可以用map添加

  1. Map<String, String> param = new HashMap<String, String>();
  2. param.put("report_period", "2020-5");
  3. param.put("pageSize", "10");
  4. param.put("pageIndex", "1");

方法中把map放入url中,调用方法时清晰方便。

发表评论

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

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

相关阅读