当前位置:   article > 正文

http请求常用工具方法_post请求工具类

post请求工具类

        这里整理了一个http的get请求和post请求的工具类,和使用方法,做个记录,以防日后忘记。

        话不多说,直接上代码:

工具类:

  1. package utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import javax.net.ssl.HttpsURLConnection;
  4. import java.io.*;
  5. import java.net.ConnectException;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9. import java.util.List;
  10. import java.util.Map;
  11. public class HttpRequest {
  12. /**
  13. * 向指定URL发送GET方法的请求
  14. * @param url
  15. * 发送请求的URL
  16. * @param param
  17. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  18. * @return URL 所代表远程资源的响应结果
  19. */
  20. public static String sendGet(String url, String param) {
  21. String result = "";
  22. BufferedReader in = null;
  23. try {
  24. String urlNameString = url + "?" + param;
  25. System.out.println(urlNameString);
  26. URL realUrl = new URL(urlNameString);
  27. // 打开和URL之间的连接
  28. URLConnection connection = realUrl.openConnection();
  29. // 设置通用的请求属性
  30. connection.setRequestProperty("accept", "*/*");
  31. connection.setRequestProperty("connection", "Keep-Alive");
  32. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  33. // 建立实际的连接
  34. connection.connect();
  35. // 获取所有响应头字段
  36. Map<String, List<String>> map = connection.getHeaderFields();
  37. // 遍历所有的响应头字段
  38. for (String key : map.keySet()) {
  39. System.out.println(key + "--->" + map.get(key));
  40. }
  41. // 定义 BufferedReader输入流来读取URL的响应
  42. in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  43. String line;
  44. while ((line = in.readLine()) != null) {
  45. result += line;
  46. }
  47. } catch (Exception e) {
  48. System.out.println("发送GET请求出现异常!" + e);
  49. e.printStackTrace();
  50. }
  51. // 使用finally块来关闭输入流
  52. finally {
  53. try {
  54. if (in != null) {
  55. in.close();
  56. }
  57. } catch (Exception e2) {
  58. e2.printStackTrace();
  59. }
  60. }
  61. return result;
  62. }
  63. /**
  64. * 向指定 URL 发送POST方法的请求
  65. *
  66. * @param url
  67. * 发送请求的 URL
  68. * @param param
  69. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  70. * @return 所代表远程资源的响应结果
  71. */
  72. public static String sendPost(String url, String param) {
  73. PrintWriter out = null;
  74. BufferedReader in = null;
  75. String result = "";
  76. try {
  77. URL realUrl = new URL(url);
  78. // 打开和URL之间的连接
  79. URLConnection conn = realUrl.openConnection();
  80. // 设置通用的请求属性
  81. conn.setRequestProperty("accept", "*/*");
  82. conn.setRequestProperty("connection", "Keep-Alive");
  83. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  84. //设置头信息
  85. conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
  86. // 发送POST请求必须设置如下两行
  87. conn.setDoOutput(true);
  88. conn.setDoInput(true);
  89. // 获取URLConnection对象对应的输出流
  90. out = new PrintWriter(conn.getOutputStream());
  91. // 发送请求参数
  92. out.print(param);
  93. // flush输出流的缓冲
  94. out.flush();
  95. // 定义BufferedReader输入流来读取URL的响应
  96. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  97. String line;
  98. while ((line = in.readLine()) != null) {
  99. result += line;
  100. }
  101. } catch (Exception e) {
  102. System.out.println("发送 POST 请求出现异常!" + e);
  103. e.printStackTrace();
  104. }
  105. // 使用finally块来关闭输出流、输入流
  106. finally {
  107. try {
  108. if (out != null) {
  109. out.close();
  110. }
  111. if (in != null) {
  112. in.close();
  113. }
  114. } catch (IOException ex) {
  115. ex.printStackTrace();
  116. }
  117. }
  118. return result;
  119. }
  120. /**
  121. * post/GET远程请求接口并得到返回结果
  122. *
  123. * @param requestUrl 请求地址
  124. * @param requestMethod 请求方法post/GET
  125. * @return
  126. */
  127. public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr,String contentType) {
  128. JSONObject jsonObject = null;
  129. StringBuffer buffer = new StringBuffer();
  130. try {
  131. URL url = new URL(requestUrl);
  132. HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
  133. httpUrlConn.setDoOutput(true);
  134. httpUrlConn.setDoInput(true);
  135. httpUrlConn.setUseCaches(false);
  136. // 设置请求方式(GET/POST)
  137. httpUrlConn.setRequestMethod(requestMethod);
  138. //设置头信息
  139. // httpUrlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
  140. httpUrlConn.setRequestProperty("Content-Type",contentType);
  141. httpUrlConn.setRequestProperty("Accept","application/json;charset=UTF-8");
  142. // 设置连接主机服务器的超时时间:15000毫秒
  143. httpUrlConn.setConnectTimeout(15000);
  144. // 设置读取远程返回的数据时间:60000毫秒
  145. httpUrlConn.setReadTimeout(60000);
  146. if ("GET".equalsIgnoreCase(requestMethod)){
  147. httpUrlConn.connect();
  148. }
  149. // 当有数据需要提交时
  150. if (null != outputStr) {
  151. OutputStream outputStream = httpUrlConn.getOutputStream();
  152. // 注意编码格式,防止中文乱码
  153. outputStream.write(outputStr.getBytes("UTF-8"));
  154. outputStream.close();
  155. }
  156. // 将返回的输入流转换成字符串
  157. InputStream inputStream = httpUrlConn.getInputStream();
  158. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  159. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  160. String str = null;
  161. while ((str = bufferedReader.readLine()) != null) {
  162. buffer.append(str);
  163. }
  164. bufferedReader.close();
  165. inputStreamReader.close();
  166. // 释放资源
  167. inputStream.close();
  168. inputStream = null;
  169. httpUrlConn.disconnect();
  170. jsonObject = JSONObject.parseObject(buffer.toString());
  171. } catch (ConnectException ce) {
  172. } catch (Exception e) {
  173. }
  174. return jsonObject;
  175. }
  176. }

调用工具类:

  1. @ResponseBody
  2. @RequestMapping(value = "/getGPT",produces = {"application/text;charset=UTF-8"})
  3. public JSON getGPT() throws IOException {
  4. String requestMethod = "POST";
  5. String body = URLEncoder.encode("junshi","UTF-8");//设置要传的信息
  6. //String url = "https://localhost/api/v1/message/rescue?first=1&keyword1=1&keyword2=2&keyword3=3&keyword4=4&keyword5=5&remark=1";//get请求时格式
  7. String url = "http://v.juhe.cn/toutiao/index";//post请求时格式
  8. //测试:访问聚合数据的地区新闻api
  9. String outputStr = "key=0b3ce1c6f00e322ef4e016675ad5cb2a&type="+body;//post请求时使用outputStr参数
  10. JSON json = HttpRequest.httpRequest(url,requestMethod,outputStr,"application/x-www-form-urlencoded;charset=UTF-8");
  11. System.out.println(json);
  12. return json;
  13. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号