HTTPRequestUtils.java 6.8 KB

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