HttpUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package com.ydtech.utils;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.http.HttpRequest;
  4. import cn.hutool.http.HttpResponse;
  5. import cn.hutool.json.JSONUtil;
  6. import com.alibaba.fastjson.JSONObject;
  7. import org.apache.commons.httpclient.HttpException;
  8. import org.apache.commons.httpclient.HttpStatus;
  9. import org.apache.commons.httpclient.methods.PostMethod;
  10. import org.apache.commons.httpclient.methods.multipart.FilePart;
  11. import org.apache.commons.httpclient.HttpClient;
  12. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
  13. import org.apache.commons.httpclient.methods.multipart.Part;
  14. import org.apache.commons.httpclient.methods.multipart.StringPart;
  15. import org.slf4j.Logger;
  16. import java.io.*;
  17. import java.net.HttpURLConnection;
  18. import java.net.URL;
  19. import java.util.HashMap;
  20. import java.util.Map;
  21. /**
  22. * @ClassName HttpUtil
  23. * @Description: TODO
  24. * @Author
  25. * @Date 2021/5/25
  26. **/
  27. public class HttpUtil {
  28. /**
  29. * 发起https请求并获取结果
  30. *
  31. * @param requestUrl 请求地址
  32. * @param requestMethod 请求方式(GET、POST)
  33. * @param outputStr 提交的数据
  34. * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
  35. */
  36. public static JSONObject HttpRequest(String request, String RequestMethod, String output) {
  37. @SuppressWarnings("unused")
  38. JSONObject jsonObject = null;
  39. StringBuffer buffer = new StringBuffer();
  40. try {
  41. //建立连接
  42. URL url = new URL(request);
  43. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  44. connection.setDoOutput(true);
  45. connection.setDoInput(true);
  46. connection.setUseCaches(false);
  47. // connection.setRequestMethod(RequestMethod);
  48. //设置请求内容编码格式
  49. connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
  50. connection.setRequestProperty("Accept", "application/json;charset=UTF-8");
  51. if (output != null) {
  52. OutputStream out = connection.getOutputStream();
  53. out.write(output.getBytes("UTF-8"));
  54. out.close();
  55. }
  56. //流处理
  57. InputStream input = connection.getInputStream();
  58. // InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
  59. BufferedReader reader = new BufferedReader(new InputStreamReader(input, "GBK"));
  60. String line;
  61. while ((line = reader.readLine()) != null) {
  62. buffer.append(line);
  63. }
  64. //关闭连接、释放资源
  65. reader.close();
  66. input.close();
  67. connection.disconnect();
  68. } catch (Exception e) {
  69. }
  70. return jsonObject;
  71. }
  72. /**
  73. * 带header和json作为body的post
  74. * @param url
  75. * @param bodyStr body传的json
  76. *
  77. * @author: lig
  78. * @date: 2023年08月14日 0014
  79. */
  80. public static String sendPost(String url,String bodyStr){
  81. System.err.println("请求[post、json、body]参数:"+bodyStr);
  82. HttpRequest request = HttpRequest.post(url)
  83. .header("Content-Type", "application/json")//以json的方式传递
  84. //     .header("authorization","Bearer abcdefghijklmnopqrstuvwxyz")
  85. .body(bodyStr);
  86. HttpResponse response = request.execute();
  87. String respStr = response.body();
  88. System.err.println("返回[post、json、body]参数:"+ respStr);
  89. return respStr;
  90. }
  91. /**
  92. * 带header和json作为body的post
  93. * @param url
  94. * @param bodyStr body传的json
  95. *
  96. * @author: lig
  97. * @date: 2023年08月14日 0014
  98. */
  99. public static String sendPost(String url,String bodyStr,Logger log,String apiName){
  100. log.debug(apiName+"\n请求参数:"+bodyStr);
  101. HttpRequest request = HttpRequest.post(url)
  102. .header("Content-Type", "application/json")//以json的方式传递
  103. //     .header("authorization","Bearer abcdefghijklmnopqrstuvwxyz")
  104. .body(bodyStr);
  105. HttpResponse response = request.execute();
  106. String respStr = response.body();
  107. log.debug(apiName+"\n返回参数:"+respStr);
  108. return respStr;
  109. }
  110. /**
  111. * 带header和json作为body的post
  112. * @param url
  113. * @param bodyStr body传的json
  114. * @param params form传的参数
  115. *
  116. * @author: lig
  117. * @date: 2023年08月14日 0014
  118. */
  119. public static String sendPost(String url,String bodyStr,Map params){
  120. HttpRequest request = HttpRequest.post(url)
  121. .header("Content-Type", "application/json")//以json的方式传递
  122. //     .header("authorization","Bearer abcdefghijklmnopqrstuvwxyz")
  123. .body(bodyStr);
  124. request.form(params);
  125. HttpResponse response = request.execute();
  126. String respStr = response.body();
  127. return respStr;
  128. }
  129. /**
  130. * post from
  131. * @param url
  132. * @param formMap 附件需要传的类型FilePart
  133. *
  134. * @author: lig
  135. * @date: 2023-08-21
  136. */
  137. public static String sendPostFrom(String url,Map<String, Object> formMap,Logger log,String apiName){
  138. System.err.println("请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
  139. log.info(apiName + ",请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
  140. HttpRequest request = HttpRequest.post(url);
  141. request.header("Content-Type", "multipart/form-data; ");
  142. // // 添加文件参数
  143. // FilePart file1 = new FilePart("file1", new File("path/to/file1.jpg"));
  144. request.form(formMap);
  145. HttpResponse response = request.execute();
  146. // 处理服务器响应
  147. if (response.isOk()) {
  148. String respStr = response.body();
  149. log.info(apiName + "返回[post、json、body]参数:"+ respStr);
  150. return respStr;
  151. }
  152. return null;
  153. }
  154. /**
  155. * post from
  156. * @param url
  157. * @param formMap 附件需要传的类型FilePart
  158. *
  159. * @author: lig
  160. * @date: 2023-08-21
  161. */
  162. public static String sendPostFrom(String url,Map<String, Object> formMap){
  163. System.err.println("请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
  164. // log.info(apiName + ",请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
  165. HttpRequest request = HttpRequest.post(url);
  166. request.header("Content-Type", "multipart/form-data; ");
  167. // // 添加文件参数
  168. // FilePart file1 = new FilePart("file1", new File("path/to/file1.jpg"));
  169. request.form(formMap);
  170. HttpResponse response = request.execute();
  171. // 处理服务器响应
  172. if (response.isOk()) {
  173. String respStr = response.body();
  174. // log.info(apiName + "返回[post、json、body]参数:"+ respStr);
  175. return respStr;
  176. }
  177. return null;
  178. }
  179. /**
  180. * post from
  181. * @param url
  182. * @param formMap 附件需要传的类型FilePart
  183. *
  184. * @author: lig
  185. * @date: 2023-08-21
  186. */
  187. public static String sendPostFromFile(Part[] parts,String url){
  188. HttpClient httpClient = new HttpClient();
  189. PostMethod postMethod = new PostMethod(url);
  190. postMethod.getParams().setContentCharset("UTF-8");
  191. // postMethod.setParameter();
  192. String response = "";
  193. try {
  194. // Part[] parts = new Part[]{ new FilePart("file111", file) };
  195. postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
  196. int statusCode = httpClient.executeMethod(postMethod);
  197. if (statusCode == HttpStatus.SC_OK) {
  198. response = postMethod.getResponseBodyAsString();
  199. System.out.println("Upload successful. Response: " + response);
  200. return response;
  201. // return response;
  202. } else {
  203. System.out.println("Upload failed. Status code: " + statusCode);
  204. }
  205. } catch (FileNotFoundException e) {
  206. throw new RuntimeException(e);
  207. } catch (HttpException e) {
  208. throw new RuntimeException(e);
  209. } catch (IOException e) {
  210. throw new RuntimeException(e);
  211. }
  212. return response;
  213. }
  214. // public static void main(String[] args) {
  215. // String url = "https://devyun.guorenpcic.com/api/grecar/photo/upload";
  216. // Map<String, Object> formMap = new HashMap<>();
  217. // formMap.put("businessNo","2322");
  218. // formMap.put("operatorCode","32323");
  219. // formMap.put("comCode","22323");
  220. // formMap.put("fileGroup","DZ");
  221. //
  222. // try {
  223. // FilePart file1 = new FilePart("file1", new File("D:/Desktop/123.png"));
  224. // formMap.put("file",file1);
  225. // } catch (FileNotFoundException e) {
  226. // throw new RuntimeException(e);
  227. // }
  228. //
  229. // sendPostFrom(url,formMap);
  230. // }
  231. public static void main(String[] args) {
  232. HttpClient httpClient = new HttpClient();
  233. String url = "https://devyun.guorenpcic.com/api/grecar/photo/upload";
  234. PostMethod postMethod = new PostMethod(url);
  235. postMethod.getParams().setContentCharset("UTF-8");
  236. // postMethod.getParams().setParameter("businessNo", "T233075000507000205");
  237. // postMethod.getParams().setParameter("operatorCode", "S3000032");
  238. // postMethod.getParams().setParameter("comCode", "307500A3");
  239. // postMethod.getParams().setParameter("fileGroup", "DZ");
  240. ;
  241. // File file = new File("D:/upload/image/2023/09/12/f27b4fe4e1fd4f2bfa57b5a560dc792d.jpg");
  242. File file = new File("D:/upload/image/2023/09/25/87b4db2aa2e209b77923238e88088c2d.png");
  243. try {
  244. // Part[] parts = { new FilePart("file", file) };
  245. Part[] parts = { new FilePart("file", file)
  246. ,new StringPart("businessNo","T233075000507000225")
  247. // ,new StringPart("businessNo","T233075000507000205")
  248. ,new StringPart("operatorCode","S3000032")
  249. ,new StringPart("comCode","307500A3")
  250. ,new StringPart("fileGroup","DZ")
  251. };
  252. postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
  253. // postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
  254. int statusCode = httpClient.executeMethod(postMethod);
  255. if (statusCode == HttpStatus.SC_OK) {
  256. String response = postMethod.getResponseBodyAsString();
  257. System.out.println("Upload successful. Response: " + response);
  258. } else {
  259. System.out.println("Upload failed. Status code: " + statusCode);
  260. }
  261. } catch (Exception e) {
  262. e.printStackTrace();
  263. } finally {
  264. postMethod.releaseConnection();
  265. }
  266. }
  267. }