Java实现HttpClient发送GET、POST请求(https、http)1、引⼊相关依赖包
jar包下载:
maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2、主要类HttpClientService
1package com.sinotn.service;
2
3import com.alibaba.fastjson.JSONObject;
4import org.apache.http.HttpEntity;
5import org.apache.http.NameValuePair;
6import org.apache.ity.UrlEncodedFormEntity;
7import org.apache.hods.CloseableHttpResponse;
8import org.apache.hods.HttpGet;
9import org.apache.hods.HttpPost;
10import org.apache.http.client.utils.URIBuilder;
11import org.ity.StringEntity;
12import org.apache.http.impl.client.CloseableHttpClient;
13import org.apache.http.impl.client.HttpClients;
14import org.ssage.BasicHeader;
15import org.ssage.BasicNameValuePair;
16import org.apache.http.util.EntityUtils;
17import org.slf4j.Logger;
18import org.slf4j.LoggerFactory;
19import java.util.ArrayList;
20import java.util.List;
21
22/**
23 * HttpClient发送GET、POST请求
24 * @Author libin
25 * @CreateDate 2018.5.28 16:56
26*/
27public class HttpClientService {
28
29private static final Logger LOGGER = Logger(HttpClientService.class);
30/**
31    * 返回成功状态码
32*/
33private static final int SUCCESS_CODE = 200;
34
35/**
36    * 发送GET请求
37    * @param url  请求url
38    * @param nameValuePairList    请求参数
39    * @return JSON或者字符串
40    * @throws Exception
41*/
42public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{
43        JSONObject jsonObject = null;
44        CloseableHttpClient client = null;
46try{
47/**
48            * 创建HttpClient对象
49*/
50            client = ateDefault();
51/**
52            * 创建URIBuilder
53*/
54            URIBuilder uriBuilder = new URIBuilder(url);
55/**
56            * 设置参数
57*/
58            uriBuilder.addParameters(nameValuePairList);
59/**
60            * 创建HttpGet
61*/
62            HttpGet httpGet = new HttpGet(uriBuilder.build());
63/**
64            * 设置请求头部编码
65*/
66            httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 67/**
68            * 设置返回编码
69*/
70            httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
71/**
72            * 请求服务
73*/
74            response = ute(httpGet);
75/**
76            * 获取响应吗
77*/
78int statusCode = StatusLine().getStatusCode();
79
80if (SUCCESS_CODE == statusCode){
81/**
82                * 获取返回对象
83*/
84                HttpEntity entity = Entity();
85/**
86                * 通过EntityUitls获取返回内容
87*/
88                String result = String(entity,"UTF-8");
89/**
90                * 转换成json,根据合法性返回json或者字符串
91*/
92try{
93                    jsonObject = JSONObject.parseObject(result);
94return jsonObject;
95                }catch (Exception e){
96return result;
97                }
98            }else{
99                ("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");
100            }
101        }catch (Exception e){
102            ("HttpClientService-line: {}, Exception: {}", 100, e);
103        } finally {
104            response.close();
105            client.close();
fastjson字符串转数组106        }
107return null;
108    }
109
110/**
111    * 发送POST请求
112    * @param url
113    * @param nameValuePairList
114    * @return JSON或者字符串
115    * @throws Exception
117public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{
118        JSONObject jsonObject = null;
119        CloseableHttpClient client = null;
120        CloseableHttpResponse response = null;
121try{
122/**
123            *  创建⼀个httpclient对象
124*/
125            client = ateDefault();
126/**
127            * 创建⼀个post对象
128*/
129            HttpPost post = new HttpPost(url);
130/**
131            * 包装成⼀个Entity对象
132*/
133            StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
134/**
135            * 设置请求的内容
136*/
137            post.setEntity(entity);
138/**
139            * 设置请求的报⽂头部的编码
140*/
141            post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 142/**
143            * 设置请求的报⽂头部的编码
144*/
145            post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
146/**
147            * 执⾏post请求
148*/
149            response = ute(post);
150/**
151            * 获取响应码
152*/
153int statusCode = StatusLine().getStatusCode();
154if (SUCCESS_CODE == statusCode){
155/**
156                * 通过EntityUitls获取返回内容
157*/
158                String result = Entity(),"UTF-8");
159/**
160                * 转换成json,根据合法性返回json或者字符串
161*/
162try{
163                    jsonObject = JSONObject.parseObject(result);
164return jsonObject;
165                }catch (Exception e){
166return result;
167                }
168            }else{
169                ("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
170            }
171        }catch (Exception e){
172            ("HttpClientService-line: {}, Exception:{}", 149, e);
173        }finally {
174            response.close();
175            client.close();
176        }
177return null;
178    }
179
180/**
181    * 组织请求参数{参数名和参数值下标保持⼀致}
182    * @param params    参数名数组
183    * @param values    参数值数组
184    * @return参数对象
185*/
186public static List<NameValuePair> getParams(Object[] params, Object[] values){
188        * 校验参数合法性
189*/
190boolean flag = params.length>0 && values.length>0 &&  params.length == values.length;
191if (flag){
192            List<NameValuePair> nameValuePairList = new ArrayList<>();
193for(int i =0; i<params.length; i++){
194                nameValuePairList.add(new BasicNameValuePair(params[i].toString(),values[i].toString())); 195            }
196return nameValuePairList;
197        }else{
198            ("HttpClientService-line: {}, errorMsg:{}", 197, "请求参数为空且参数长度不⼀致"); 199        }
200return null;
201    }
202 }
3、调⽤⽅法
1package com.sinotn.service.impl;
2
3import com.sinotn.service.HttpClientService;
4import org.apache.http.NameValuePair;
5
6import java.util.List;
7
8/**
9 * 发送post/get 测试类
10*/
11public class Test {
12
13public static void main(String[] args) throws Exception{
14        String url = "要请求的url地址";
15/**
16        * 参数值
17*/
18        Object [] params = new Object[]{"param1","param2"};
19/**
20        * 参数名
21*/
22        Object [] values = new Object[]{"value1","value2"};
23/**
24        * 获取参数对象
25*/
26        List<NameValuePair> paramsList = Params(params, values);
27/**
28        * 发送get
29*/
30        Object result = HttpClientService.sendGet(url, paramsList);
31/**
32        * 发送post
33*/
34        Object result2 = HttpClientService.sendPost(url, paramsList);
35
36        System.out.println("GET返回信息:" + result);
37        System.out.println("POST返回信息:" + result2);
38    }
39 }
4、对于发送https
为了避免需要证书,所以⽤⼀个类继承DefaultHttpClient类,忽略校验过程。
写⼀个SSLClient类,继承⾄HttpClient
1import CertificateException;
2import X509Certificate;
4import javax.ssl.TrustManager;
5import javax.ssl.X509TrustManager;
6import org.ClientConnectionManager;
7import org.scheme.Scheme;
8import org.scheme.SchemeRegistry;
9import org.ssl.SSLSocketFactory;
10import org.apache.http.impl.client.DefaultHttpClient;
11//⽤于进⾏Https请求的HttpClient
12public class SSLClient extends DefaultHttpClient{
13public SSLClient() throws Exception{
14super();
15        SSLContext ctx = Instance("TLS");
16        X509TrustManager tm = new X509TrustManager() {
17                @Override
18public void checkClientTrusted(X509Certificate[] chain,
19                        String authType) throws CertificateException {
20                }
21                @Override
22public void checkServerTrusted(X509Certificate[] chain,
23                        String authType) throws CertificateException {
24                }
25                @Override
26public X509Certificate[] getAcceptedIssuers() {
27return null;
28                }
29        };
30        ctx.init(null, new TrustManager[]{tm}, null);
31        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
32        ClientConnectionManager ccm = ConnectionManager();
33        SchemeRegistry sr = SchemeRegistry();
34        sr.register(new Scheme("https", 443, ssf));
35    }
36 }
5、对于https调⽤

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。