| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319 |
- package com.ydtech.utils;
- import cn.hutool.core.bean.BeanUtil;
- import cn.hutool.http.HttpRequest;
- import cn.hutool.http.HttpResponse;
- import cn.hutool.json.JSONUtil;
- import com.alibaba.fastjson.JSONObject;
- import org.apache.commons.httpclient.HttpException;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.apache.commons.httpclient.methods.multipart.FilePart;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
- import org.apache.commons.httpclient.methods.multipart.Part;
- import org.apache.commons.httpclient.methods.multipart.StringPart;
- import org.slf4j.Logger;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * @ClassName HttpUtil
- * @Description: TODO
- * @Author
- * @Date 2021/5/25
- **/
- public class HttpUtil {
- /**
- * 发起https请求并获取结果
- *
- * @param requestUrl 请求地址
- * @param requestMethod 请求方式(GET、POST)
- * @param outputStr 提交的数据
- * @return JSONObject(通过JSONObject.get ( key)的方式获取json对象的属性值)
- */
- public static JSONObject HttpRequest(String request, String RequestMethod, String output) {
- @SuppressWarnings("unused")
- JSONObject jsonObject = null;
- StringBuffer buffer = new StringBuffer();
- try {
- //建立连接
- URL url = new URL(request);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- // connection.setRequestMethod(RequestMethod);
- //设置请求内容编码格式
- connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
- connection.setRequestProperty("Accept", "application/json;charset=UTF-8");
- if (output != null) {
- OutputStream out = connection.getOutputStream();
- out.write(output.getBytes("UTF-8"));
- out.close();
- }
- //流处理
- InputStream input = connection.getInputStream();
- // InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
- BufferedReader reader = new BufferedReader(new InputStreamReader(input, "GBK"));
- String line;
- while ((line = reader.readLine()) != null) {
- buffer.append(line);
- }
- //关闭连接、释放资源
- reader.close();
- input.close();
- connection.disconnect();
- } catch (Exception e) {
- }
- return jsonObject;
- }
- /**
- * 带header和json作为body的post
- * @param url
- * @param bodyStr body传的json
- *
- * @author: lig
- * @date: 2023年08月14日 0014
- */
- public static String sendPost(String url,String bodyStr){
- System.err.println("请求[post、json、body]参数:"+bodyStr);
- HttpRequest request = HttpRequest.post(url)
- .header("Content-Type", "application/json")//以json的方式传递
- // .header("authorization","Bearer abcdefghijklmnopqrstuvwxyz")
- .body(bodyStr);
- HttpResponse response = request.execute();
- String respStr = response.body();
- System.err.println("返回[post、json、body]参数:"+ respStr);
- return respStr;
- }
- /**
- * 带header和json作为body的post
- * @param url
- * @param bodyStr body传的json
- *
- * @author: lig
- * @date: 2023年08月14日 0014
- */
- public static String sendPost(String url,String bodyStr,Logger log,String apiName){
- log.debug(apiName+"\n请求参数:"+bodyStr);
- HttpRequest request = HttpRequest.post(url)
- .header("Content-Type", "application/json")//以json的方式传递
- // .header("authorization","Bearer abcdefghijklmnopqrstuvwxyz")
- .body(bodyStr);
- HttpResponse response = request.execute();
- String respStr = response.body();
- log.debug(apiName+"\n返回参数:"+respStr);
- return respStr;
- }
- /**
- * 带header和json作为body的post
- * @param url
- * @param bodyStr body传的json
- * @param params form传的参数
- *
- * @author: lig
- * @date: 2023年08月14日 0014
- */
- public static String sendPost(String url,String bodyStr,Map params){
- HttpRequest request = HttpRequest.post(url)
- .header("Content-Type", "application/json")//以json的方式传递
- // .header("authorization","Bearer abcdefghijklmnopqrstuvwxyz")
- .body(bodyStr);
- request.form(params);
- HttpResponse response = request.execute();
- String respStr = response.body();
- return respStr;
- }
- /**
- * post from
- * @param url
- * @param formMap 附件需要传的类型FilePart
- *
- * @author: lig
- * @date: 2023-08-21
- */
- public static String sendPostFrom(String url,Map<String, Object> formMap,Logger log,String apiName){
- System.err.println("请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
- log.info(apiName + ",请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
- HttpRequest request = HttpRequest.post(url);
- request.header("Content-Type", "multipart/form-data; ");
- // // 添加文件参数
- // FilePart file1 = new FilePart("file1", new File("path/to/file1.jpg"));
- request.form(formMap);
- HttpResponse response = request.execute();
- // 处理服务器响应
- if (response.isOk()) {
- String respStr = response.body();
- log.info(apiName + "返回[post、json、body]参数:"+ respStr);
- return respStr;
- }
- return null;
- }
- /**
- * post from
- * @param url
- * @param formMap 附件需要传的类型FilePart
- *
- * @author: lig
- * @date: 2023-08-21
- */
- public static String sendPostFrom(String url,Map<String, Object> formMap){
- System.err.println("请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
- // log.info(apiName + ",请求[post、json、body]参数:"+ JSONUtil.toJsonStr(formMap));
- HttpRequest request = HttpRequest.post(url);
- request.header("Content-Type", "multipart/form-data; ");
- // // 添加文件参数
- // FilePart file1 = new FilePart("file1", new File("path/to/file1.jpg"));
- request.form(formMap);
- HttpResponse response = request.execute();
- // 处理服务器响应
- if (response.isOk()) {
- String respStr = response.body();
- // log.info(apiName + "返回[post、json、body]参数:"+ respStr);
- return respStr;
- }
- return null;
- }
- /**
- * post from
- * @param url
- * @param formMap 附件需要传的类型FilePart
- *
- * @author: lig
- * @date: 2023-08-21
- */
- public static String sendPostFromFile(Part[] parts,String url){
- HttpClient httpClient = new HttpClient();
- PostMethod postMethod = new PostMethod(url);
- postMethod.getParams().setContentCharset("UTF-8");
- // postMethod.setParameter();
- String response = "";
- try {
- // Part[] parts = new Part[]{ new FilePart("file111", file) };
- postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
- int statusCode = httpClient.executeMethod(postMethod);
- if (statusCode == HttpStatus.SC_OK) {
- response = postMethod.getResponseBodyAsString();
- System.out.println("Upload successful. Response: " + response);
- return response;
- // return response;
- } else {
- System.out.println("Upload failed. Status code: " + statusCode);
- }
- } catch (FileNotFoundException e) {
- throw new RuntimeException(e);
- } catch (HttpException e) {
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return response;
- }
- // public static void main(String[] args) {
- // String url = "https://devyun.guorenpcic.com/api/grecar/photo/upload";
- // Map<String, Object> formMap = new HashMap<>();
- // formMap.put("businessNo","2322");
- // formMap.put("operatorCode","32323");
- // formMap.put("comCode","22323");
- // formMap.put("fileGroup","DZ");
- //
- // try {
- // FilePart file1 = new FilePart("file1", new File("D:/Desktop/123.png"));
- // formMap.put("file",file1);
- // } catch (FileNotFoundException e) {
- // throw new RuntimeException(e);
- // }
- //
- // sendPostFrom(url,formMap);
- // }
- public static void main(String[] args) {
- HttpClient httpClient = new HttpClient();
- String url = "https://devyun.guorenpcic.com/api/grecar/photo/upload";
- PostMethod postMethod = new PostMethod(url);
- postMethod.getParams().setContentCharset("UTF-8");
- // postMethod.getParams().setParameter("businessNo", "T233075000507000205");
- // postMethod.getParams().setParameter("operatorCode", "S3000032");
- // postMethod.getParams().setParameter("comCode", "307500A3");
- // postMethod.getParams().setParameter("fileGroup", "DZ");
- ;
- // File file = new File("D:/upload/image/2023/09/12/f27b4fe4e1fd4f2bfa57b5a560dc792d.jpg");
- File file = new File("D:/upload/image/2023/09/25/87b4db2aa2e209b77923238e88088c2d.png");
- try {
- // Part[] parts = { new FilePart("file", file) };
- Part[] parts = { new FilePart("file", file)
- ,new StringPart("businessNo","T233075000507000225")
- // ,new StringPart("businessNo","T233075000507000205")
- ,new StringPart("operatorCode","S3000032")
- ,new StringPart("comCode","307500A3")
- ,new StringPart("fileGroup","DZ")
- };
- postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
- // postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
- int statusCode = httpClient.executeMethod(postMethod);
- if (statusCode == HttpStatus.SC_OK) {
- String response = postMethod.getResponseBodyAsString();
- System.out.println("Upload successful. Response: " + response);
- } else {
- System.out.println("Upload failed. Status code: " + statusCode);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- postMethod.releaseConnection();
- }
- }
- }
|