Http调用接口工具类

版权声明:本文为博主转载文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_42513284/article/details/91949287

文章目录
一. Http调用接口工具类
1.pom 依赖
2.工具类1(一般的get、post、下载)
3.工具类2(处理完请求后转至目标接口:get、post)
4.获取请求参数
一. Http调用接口工具类
1.pom 依赖

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>


1
2
3
4
5
2.工具类1(一般的get、post、下载)

package com.qin.common.util;

import com.qin.util.ResponseDto;
import com.qin.JsonUtils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 封装http方法
 * 
 * @author wzb
 *
 */
public class HttpClientUtil {

    // 本地异常日志记录对象
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 执行post方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static ResponseDto doPost(String url, Map<String, Object> params) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);

            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);

            client.executeMethod(post);
            String respStr = post.getResponseBodyAsString();
            responseDto = JsonUtils.parse(respStr, ResponseDto.class);
            post.releaseConnection();
            return responseDto;
        } catch (Exception e1) {
            e1.printStackTrace();
            responseDto.setErrcode("0");
            responseDto.setErrmsg("post方法,远程调用时出错!");
            return responseDto;
        }
    }

    /**
     * 执行post方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static String doPost1(String url, Map<String, Object> params) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);
            client.executeMethod(post);
            String respStr =  new String(post.getResponseBody(), StandardCharsets.UTF_8);
            post.releaseConnection();
            return respStr;
        } catch (Exception e1) {
            e1.printStackTrace();
            responseDto.setErrcode("0");
            responseDto.setErrmsg("post方法,远程调用时出错!");
            return responseDto.toString();
        }
    }

    /**
     * 执行post方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static void doResponsePost(String url, Map<String, Object> params, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        HttpClient client = new HttpClient();
        try {
            PostMethod post = new PostMethod(url);
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);
            client.executeMethod(post);
            byte[] respStr = post.getResponseBody();
            is = new ByteArrayInputStream(respStr);
            os = response.getOutputStream();
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                response.flushBuffer();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * 执行下载附件方法
     * 
     * @param url
     * @param params
     * @return
     */
    public static void doAppDownLoadPost(String url, Map<String, Object> params, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        HttpClient client = new HttpClient();
        try {
            PostMethod post = new PostMethod(url);
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);

            client.executeMethod(post);
            byte[] respStr = post.getResponseBody();

            Header fileName = post.getResponseHeader("fileName");// 文件名称
            is = new ByteArrayInputStream(respStr);
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName.getValue());
            os = response.getOutputStream();
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                response.flushBuffer();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * 执行post方法
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost3(String url, Map<String, Object> params, HttpServletRequest request) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(url);
            post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            post.addRequestHeader("Cookie",request.getHeader("Cookie"));
            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
            for (String key : params.keySet()) {
                String value = params.get(key) == null ? "" : params.get(key).toString();
                NameValuePair param = new NameValuePair(key, value);
                nameValuePairs[count] = param;
                count++;
            }
            post.setRequestBody(nameValuePairs);
            client.executeMethod(post);
            String respStr =  new String(post.getResponseBody(), StandardCharsets.UTF_8);
            post.releaseConnection();
            return respStr;
        } catch (Exception e1) {
            e1.printStackTrace();
            responseDto.setErrcode("0");
            responseDto.setErrmsg("post方法,远程调用时出错!");
            return responseDto.toString();
        }
    }

    /**
     * 执行get方法
     *
     * @param url
     * @param params
     * @return
     */
    public String doGet(String url, Map<String, Object> params) {
        ResponseDto responseDto = new ResponseDto();
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);

            int count = 0;
            NameValuePair[] nameValuePairs = new NameValuePair[params == null ? 0 : params.size()];
            if (params != null) {
                for (String key : params.keySet()) {
                    String value = params.get(key) == null ? "" : params.get(key).toString();
                    NameValuePair param = new NameValuePair(key, value);
                    nameValuePairs[count] = param;
                    count++;
                }
            }
            get.setQueryString(nameValuePairs);
            client.executeMethod(get);
            String respStr = new String(get.getResponseBody(), StandardCharsets.UTF_8);
            get.releaseConnection();
            return respStr;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            responseDto.setErrcode(AttrConstants.ERROR_CODE);
            responseDto.setErrmsg(e.getMessage());
            return responseDto.toString();
        }
    }

}

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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
3.工具类2(处理完请求后转至目标接口:get、post)

package com.qin.common.util;

import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.qin.common.server.SessionUtil;
import com.qin.util.StringUtil;

import fr.opensagres.xdocreport.utils.StringUtils;

public class HttpClientUtil {
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public String postMethod(HttpServletRequest hsrq, HttpServletResponse hsrp, String url
            , JSONObject paramMap, String paramJson) throws Exception {
        String result ="";
        // 创建默认的httpClient实例
        CloseableHttpClient httpclient = null;
            if(url.startsWith("https")) {
                httpclient = getIgnoeSSLClient();
            }else {
                httpclient = HttpClients.createDefault();
            }
//           CloseableHttpClient httpclient = HttpClients.createDefault();
           //设置请求超时时间
           RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
           // 创建httppost     
           HttpPost httppost = new HttpPost(url);
           httppost.setConfig(requestConfig);
           String ip = SessionUtil.getIpAddress(hsrq);
           httppost.setHeader("sourceId", ip);
           Enumeration<String> header = hsrq.getHeaderNames();
           while(header.hasMoreElements()) {
               String headNmae = header.nextElement();
               if(url.startsWith("https")&&!"content-length".equals(headNmae.toLowerCase())&&!"content-type".equals(headNmae.toLowerCase())&&!"host".equals(headNmae.toLowerCase())) {
                   httppost.setHeader(headNmae, hsrq.getHeader(headNmae));
               } else if(!url.startsWith("https") && !"content-length".equals(headNmae.toLowerCase())) {
                   httppost.setHeader(headNmae, hsrq.getHeader(headNmae));
               }
               /*if("content-type".equals(headNmae.toLowerCase())) {
                   httppost.setHeader(headNmae, hsrq.getHeader(headNmae));
               }*/
           }
           // 创建参数队列     
           List<NameValuePair> formparams = new ArrayList<NameValuePair>();
           if(StringUtil.isEmpty(paramJson)) {
               Set<String> keySet = paramMap.keySet();
               if(keySet.size()>0){
                   for (String param : keySet) {
                       if(StringUtils.isNotEmpty(param)){
                           formparams.add(new BasicNameValuePair(param, null == paramMap.get(param)?null:paramMap.get(param).toString()));
                       }
                   }
               }
           }
           UrlEncodedFormEntity uefEntity;
           try {   
               if(StringUtil.isEmpty(hsrq.getHeader("content-type")) || hsrq.getHeader("content-type").indexOf("application/json") == -1) {
                   uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                   httppost.setEntity(uefEntity);   
               }else {
                   StringEntity entity = new StringEntity(StringUtil.isEmpty(paramJson)?paramMap.toJSONString():paramJson,"UTF-8");
                   httppost.setEntity(entity);
               }
               CloseableHttpResponse response = httpclient.execute(httppost);
               try {
                   Header[] headers = response.getAllHeaders();
                   for(Header h:headers) {
//                       if(!"content-length".equals(h.getName().toLowerCase())) {
                           if("content-type".equals(h.getName().toLowerCase())) {
                           hsrp.setHeader(h.getName(), h.getValue());
                       }
                   }
                   hsrp.getContentType();
                   HttpEntity entity = response.getEntity();
                   if (entity != null) {
                           String temp = EntityUtils.toString(entity, "UTF-8")+"";
                       return temp;
                   }
                   return result;
               } catch (Exception e) {  
                   logger.error("send error:", e);
                   result = e.getMessage();   
               } finally {
                   response.close();
               }   
           } catch (Exception e) {   
               logger.error("send error:", e);
               result = e.getMessage();   
           } finally {
               // 关闭连接,释放资源     
               try {
                   if(null != httpclient){
                       httpclient.close();   
                   }
               } catch (IOException e) {   
                   logger.error("send error:", e);
                   result = e.getMessage();   
               }
           }
        
        return result;
    }

    public String getMethod(HttpServletRequest hsrq, HttpServletResponse hsrp, String url, JSONObject paramMap, String paramJson) throws Exception {
        String result ="";
        CloseableHttpClient httpclient = null;
        if(url.startsWith("https")) {
            httpclient = getIgnoeSSLClient();
        }else {
            // 创建默认的httpClient实例
            httpclient = HttpClients.createDefault();
        }
//        CloseableHttpClient httpclient = HttpClients.createDefault();
        //设置连接超时
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();

        URIBuilder builder = new URIBuilder(url);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if(StringUtil.isEmpty(paramJson)) {
            Set<String> keySet = paramMap.keySet();
            if(keySet.size()>0){
                for (String param : keySet) {
                    if(StringUtils.isNotEmpty(param)){
                        formparams.add(new BasicNameValuePair(param,  null == paramMap.get(param)?null:paramMap.get(param).toString()));
                    }
                }
            }
        }
        builder.addParameters(formparams);
        URI uri = builder.build();
        // 创建http GET请求
        HttpGet httpget = new HttpGet(uri);

        httpget.setConfig(requestConfig);
        String ip = SessionUtil.getIpAddress(hsrq);
        httpget.setHeader("sourceId", ip);
        Enumeration<String> header = hsrq.getHeaderNames();
        while(header.hasMoreElements()) {
            String headNmae = header.nextElement();
            if(url.startsWith("https")&&!"content-length".equals(headNmae.toLowerCase())&&!"content-type".equals(headNmae.toLowerCase())&&!"host".equals(headNmae.toLowerCase())) {
                httpget.setHeader(headNmae, hsrq.getHeader(headNmae));
            } else if(!url.startsWith("https") && !"content-length".equals(headNmae.toLowerCase())) {
                httpget.setHeader(headNmae, hsrq.getHeader(headNmae));
            }
        }

        try {
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                Header[] headers = response.getAllHeaders();
                for(Header h:headers) {
//                    if(!"content-length".equals(h.getName().toLowerCase())) {
                        if("content-type".equals(h.getName().toLowerCase())) {
                        hsrp.setHeader(h.getName(), h.getValue());
                    }
                }
                HttpEntity entity = response.getEntity();
                if (response.getStatusLine().getStatusCode() == 200) {
                    String temp = EntityUtils.toString(entity, "UTF-8")+"";
                    return temp;
                }
                return result;
            } catch (Exception e) {
                logger.error("send error:", e);
                result = e.getMessage();
            } finally {
                response.close();
            }

        } catch (Exception e) {
            logger.error("send error:", e);
            result = e.getMessage();
        } finally {
            // 关闭连接,释放资源
            try {
                if(null != httpclient){
                    httpclient.close();
                }
            } catch (IOException e) {
                logger.error("send error:", e);
                result = e.getMessage();
            }
        }

        return result;
    }

    public static String doGet(String url) throws Exception{

        CloseableHttpClient httpclient = null;
        if(url.startsWith("https")) {
            httpclient = getIgnoeSSLClient();
        }else {
            // 创建默认的httpClient实例
            httpclient = HttpClients.createDefault();
        }
        // 创建Httpclient对象
//        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
           // 创建uri
           URIBuilder builder = new URIBuilder(url);
           /*if (param != null) {
              for (String key : param.keySet()) {
                 builder.addParameter(key, param.get(key).toString());
              }
           }*/
           URI uri = builder.build();

           // 创建http GET请求
           HttpGet httpGet = new HttpGet(uri);

           // 执行请求
           response = httpclient.execute(httpGet);
           // 判断返回状态是否为200
           if (response.getStatusLine().getStatusCode() == 200) {
              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
              return resultString;
           }
        } finally {
           try {
              if (response != null) {
                 response.close();
              }
              httpclient.close();
           } catch (IOException e) {
              e.printStackTrace();
           }
        }
        return resultString;
     }
    private static CloseableHttpClient getIgnoeSSLClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        return client;
    }
}

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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
4.获取请求参数
//1.获取请求参数

public static Map<String,Object> getRequestParam(HttpServletRequest hsrq) throws Exception{
        Map<String, Object> temp = new HashMap<String, Object>();
        JSONObject json = new JSONObject();
        Map<String, String[]> mm = hsrq.getParameterMap();
        for (Entry<String, String[]> entry : mm.entrySet()) {
            String key = entry.getKey();  
            String[] value = entry.getValue(); 
            for (int i = 0; i < value.length; i++) {
                json.put(key, value[i]);
            }
        }
        String jsonString = "";
        if (json.isEmpty()) {
            try {
                jsonString = RequestUtils.getRequestJsonString(hsrq);
                json = JSON.parseObject(jsonString);
            }catch (Exception e) {
                temp.put("jsonString", jsonString);
            }
        }
        temp.put("jsonMap", json);
        return temp;
    } 

//2.RequestUtils

package com.qin.common.server;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;

public class RequestUtils {
    public RequestUtils() {
    }

    public static String getRequestJsonString(HttpServletRequest request) throws IOException {
        String submitMehtod = request.getMethod();
        if (submitMehtod.equals("GET")) {
            String queryString = request.getQueryString();
            return queryString == null ? null : (new String(queryString.getBytes("iso-8859-1"), "utf-8")).replaceAll("%22", "\"");
        } else {
            return getRequestPostStr(request);
        }
    }

    public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        } else {
            byte[] buffer = new byte[contentLength];

            int readlen;
            for(int i = 0; i < contentLength; i += readlen) {
                readlen = request.getInputStream().read(buffer, i, contentLength - i);
                if (readlen == -1) {
                    break;
                }
            }

            return buffer;
        }
    }

    public static String getRequestPostStr(HttpServletRequest request) throws IOException {
        byte[] buffer = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }

        return new String(buffer, charEncoding);
    }

    public static String getRequestRootUrl(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
}

————————————————
版权声明:本文为CSDN博主「枫灵小宇」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_42513284/article/details/91949287

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现根据HTTP接口调用工具类的基本思路如下: 1. 引入HTTP客户端库,例如Apache HttpClient或OkHttp。 2. 封装HTTP请求和响应的工具类,例如: ``` public class HttpUtils { // 发送HTTP GET请求 public static String get(String url) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); String result = EntityUtils.toString(response.getEntity()); response.close(); httpClient.close(); return result; } // 发送HTTP POST请求 public static String post(String url, Map<String, String> params) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList<>(); for (Map.Entry<String, String> entry : params.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); CloseableHttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity()); response.close(); httpClient.close(); return result; } } ``` 3. 在代码中使用HTTP工具类调用接口,例如: ``` // 发送HTTP GET请求 String result = HttpUtils.get("http://example.com/api?param1=value1&param2=value2"); // 发送HTTP POST请求 Map<String, String> params = new HashMap<>(); params.put("param1", "value1"); params.put("param2", "value2"); String result = HttpUtils.post("http://example.com/api", params); ``` 需要注意的是,Java实现根据HTTP接口调用工具类需要根据具体的业务逻辑和接口协议进行实现,需要进行接口参数的封装和解析,并进行异常处理和错误码处理。同时,还需要进行HTTP请求和响应的监控和管理,保证接口的稳定性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值