无关风月
2024-12-25 4df088ddf824625232e38c9924f7dcd45d3a4fc6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.jilongda.common.utils;
 
import com.alibaba.fastjson.JSONObject;
import com.jilongda.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
 
/**
 * @Description
 * @Author xiaochen
 * @Date 2021/11/30/03020:51
 */
@Slf4j
public class HttpClientUtil {
 
 
    public static String post(String strURL, String params, String token) {
        System.out.println(strURL);
        System.out.println(params);
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Authorization", token); // 设置token
            connection.connect();
            if (params != null && !TextUtils.isEmpty(params)) {
                byte[] writebytes = params.getBytes();
                // 设置文件长度
                //   connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = connection.getOutputStream();
                outwritestream.write(params.getBytes());
                outwritestream.flush();
                outwritestream.close();
                // Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode());
            }
            if (connection.getResponseCode() == 200) {
                log.info("<<<<<<<<<<<<<请求响应错误信息:{}", connection.getResponseMessage());
                reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                result = reader.readLine();
                log.info("<<<<<<<<<<<<<请求响应:{}", result);
            } else {
                throw new ServiceException(connection.getResponseMessage());
            }
        } catch (Exception e) {
            throw new ServiceException("http的post请求异常!" + e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
 
    /**
     * 请求发送执行
     *
     * @param httpMethd
     * @return
     */
    /**
     * PSOT JSON方式提交
     *
     * @param url    请求url
     * @param params json串
     * @return
     */
    public static String postFromJson(String url, String params, String token) {
        HttpPost request = new HttpPost(url);
        request.setHeader("Content-type", "application/json");
        request.setHeader("Accept", "application/json");
        request.setHeader("Authorization", token);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(12000)
                .setConnectTimeout(8000)
                .build();
        request.setConfig(requestConfig);
        StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
        entity.setContentType("application/json");
        request.setEntity(entity);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try (CloseableHttpResponse httpResponse = httpClient.execute(request, HttpClientContext.create())) {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.error("响应失败 statusCode:{}", statusCode);
                String result = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String message = jsonObject.getString("message");
                throw new ServiceException(message);
            } else {
                String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
                log.info("响应成功 response {}", response);
                return response;
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
 
}