HTTPRequestUtils.java 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package com.steerinfo.dil.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.ParseException;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.message.BasicHeader;
  11. import org.apache.http.protocol.HTTP;
  12. import org.apache.http.util.EntityUtils;
  13. import java.io.*;
  14. import java.net.HttpURLConnection;
  15. import java.net.URL;
  16. import java.net.URLConnection;
  17. public class HTTPRequestUtils {
  18. /**
  19. * 发送post请求
  20. *
  21. * @param url 路径
  22. * @param json 参数(json类型)
  23. * @param encoding 编码格式
  24. * @return
  25. * @throws ParseException
  26. * @throws IOException
  27. */
  28. public static String send(String url, String json, String encoding) throws ParseException, IOException {
  29. String body = "";
  30. //创建httpclient对象
  31. CloseableHttpClient client = HttpClients.createDefault();
  32. //创建post方式请求对象
  33. HttpPost httpPost = new HttpPost(url);
  34. //装填参数
  35. StringEntity s = new StringEntity(json.toString(), "utf-8");
  36. s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  37. //设置参数到请求对象中
  38. httpPost.setEntity(s);
  39. System.out.println("请求地址:" + url);
  40. System.out.println(json);
  41. httpPost.setHeader("Content-type", "application/json");
  42. httpPost.setHeader("-UserAgent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  43. //执行请求操作,并拿到结果(同步阻塞)
  44. CloseableHttpResponse response = client.execute(httpPost);
  45. System.out.println(response);
  46. //获取结果实体
  47. HttpEntity entity = response.getEntity();
  48. System.out.println(entity);
  49. if (entity != null) {
  50. //按指定编码转换结果实体为String类型
  51. body = EntityUtils.toString(entity, encoding);
  52. }
  53. EntityUtils.consume(entity);
  54. //释放链接
  55. response.close();
  56. return body;
  57. }
  58. public static String getJsonData(JSONObject jsonParam, String urls) {
  59. StringBuffer sb = new StringBuffer();
  60. try {
  61. // 创建url资源
  62. URL url = new URL(urls);
  63. // 建立http连接
  64. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  65. // 设置允许输出
  66. conn.setDoOutput(true);
  67. // 设置允许输入
  68. conn.setDoInput(true);
  69. // 设置不用缓存
  70. conn.setUseCaches(false);
  71. // 设置传递方式
  72. conn.setRequestMethod("POST");
  73. // 设置维持长连接
  74. conn.setRequestProperty("Connection", "Keep-Alive");
  75. // 设置文件字符集:
  76. conn.setRequestProperty("Charset", "UTF-8");
  77. // 转换为字节数组
  78. byte[] data = (jsonParam.toString()).getBytes();
  79. // 设置文件长度
  80. conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  81. // 设置文件类型:
  82. conn.setRequestProperty("Content-Type", "application/json");
  83. // 开始连接请求
  84. conn.connect();
  85. OutputStream out = new DataOutputStream(conn.getOutputStream());
  86. // 写入请求的字符串
  87. out.write((jsonParam.toString()).getBytes());
  88. out.flush();
  89. out.close();
  90. System.out.println(conn.getResponseCode());
  91. // 请求返回的状态
  92. if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
  93. System.out.println("连接成功");
  94. // 请求返回的数据
  95. InputStream in1 = conn.getInputStream();
  96. try {
  97. String readLine = new String();
  98. BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
  99. while ((readLine = responseReader.readLine()) != null) {
  100. sb.append(readLine).append("\n");
  101. }
  102. responseReader.close();
  103. System.out.println(sb.toString());
  104. } catch (Exception e1) {
  105. e1.printStackTrace();
  106. }
  107. } else {
  108. System.out.println("error++");
  109. }
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. }
  113. return sb.toString();
  114. }
  115. /**
  116. * 向指定 URL 发送POST方法的请求
  117. *
  118. * @param url 发送请求的 URL
  119. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  120. * @return 所代表远程资源的响应结果
  121. */
  122. public static String sendPost(String url, String param) {
  123. PrintWriter out = null;
  124. BufferedReader in = null;
  125. String result = "";
  126. try {
  127. URL realUrl = new URL(url);
  128. // 打开和URL之间的连接
  129. URLConnection conn = realUrl.openConnection();
  130. // 设置通用的请求属性
  131. conn.setRequestProperty("accept", "*/*");
  132. conn.setRequestProperty("connection", "Keep-Alive");
  133. conn.setRequestProperty("charsert", "utf-8");
  134. conn.setRequestProperty("Content-Type", "application/json");
  135. // conn.setRequestProperty("user-agent",
  136. // "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  137. // 发送POST请求必须设置如下两行
  138. conn.setDoOutput(true);
  139. conn.setDoInput(true);
  140. // 获取URLConnection对象对应的输出流
  141. out = new PrintWriter(conn.getOutputStream());
  142. // 发送请求参数
  143. out.print(param);
  144. // flush输出流的缓冲
  145. out.flush();
  146. // 定义BufferedReader输入流来读取URL的响应
  147. in = new BufferedReader(
  148. new InputStreamReader(conn.getInputStream()));
  149. String line;
  150. while ((line = in.readLine()) != null) {
  151. result += line;
  152. }
  153. } catch (Exception e) {
  154. System.out.println("发送 POST 请求出现异常!" + e);
  155. e.printStackTrace();
  156. }
  157. //使用finally块来关闭输出流、输入流
  158. finally {
  159. try {
  160. if (out != null) {
  161. out.close();
  162. }
  163. if (in != null) {
  164. in.close();
  165. }
  166. } catch (IOException ex) {
  167. ex.printStackTrace();
  168. }
  169. }
  170. return result;
  171. }
  172. }