java 执行https的请求

Posted JackGIS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 执行https的请求相关的知识,希望对你有一定的参考价值。

普通的get和post请求只能执行http的请求,遇到的了https的就歇菜了,需要SSL安全证书处理。

该方法只能用jdk1.7和1.8进行处理,jdk1.6会报Could not generate DH keypair的错误。

1、引入相关依赖包

jar包下载:httpcore4.5.5.jar    fastjson-1.2.47.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

复制代码
  1 package com.sinotn.service;
  2 
  3 import com.alibaba.fastjson.JSONObject;
  4 import org.apache.http.HttpEntity;
  5 import org.apache.http.NameValuePair;
  6 import org.apache.http.client.entity.UrlEncodedFormEntity;
  7 import org.apache.http.client.methods.CloseableHttpResponse;
  8 import org.apache.http.client.methods.HttpGet;
  9 import org.apache.http.client.methods.HttpPost;
 10 import org.apache.http.client.utils.URIBuilder;
 11 import org.apache.http.entity.StringEntity;
 12 import org.apache.http.impl.client.CloseableHttpClient;
 13 import org.apache.http.impl.client.HttpClients;
 14 import org.apache.http.message.BasicHeader;
 15 import org.apache.http.message.BasicNameValuePair;
 16 import org.apache.http.util.EntityUtils;
 17 import org.slf4j.Logger;
 18 import org.slf4j.LoggerFactory;
 19 import java.util.ArrayList;
 20 import java.util.List;
 21 
 22 /**
 23  * HttpClient发送GET、POST请求
 24  * @Author libin
 25  * @CreateDate 2018.5.28 16:56
 26  */
 27 public class HttpClientService {
 28 
 29     private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
 30     /**
 31      * 返回成功状态码
 32      */
 33     private static final int SUCCESS_CODE = 200;
 34 
 35     /**
 36      * 发送GET请求
 37      * @param url   请求url
 38      * @param nameValuePairList    请求参数
 39      * @return JSON或者字符串
 40      * @throws Exception
 41      */
 42     public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{
 43         JSONObject jsonObject = null;
 44         CloseableHttpClient client = null;
 45         CloseableHttpResponse response = null;
 46         try{
 47             /**
 48              * 创建HttpClient对象
 49              */
 50             client = HttpClients.createDefault();
 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 = client.execute(httpGet);
 75             /**
 76              * 获取响应吗
 77              */
 78             int statusCode = response.getStatusLine().getStatusCode();
 79 
 80             if (SUCCESS_CODE == statusCode){
 81                 /**
 82                  * 获取返回对象
 83                  */
 84                 HttpEntity entity = response.getEntity();
 85                 /**
 86                  * 通过EntityUitls获取返回内容
 87                  */
 88                 String result = EntityUtils.toString(entity,"UTF-8");
 89                 /**
 90                  * 转换成json,根据合法性返回json或者字符串
 91                  */
 92                 try{
 93                     jsonObject = JSONObject.parseObject(result);
 94                     return jsonObject;
 95                 }catch (Exception e){
 96                     return result;
 97                 }
 98             }else{
 99                 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");
100             }
101         }catch (Exception e){
102             LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
103         } finally {
104             response.close();
105             client.close();
106         }
107         return null;
108     }
109 
110     /**
111      * 发送POST请求
112      * @param url
113      * @param nameValuePairList
114      * @return JSON或者字符串
115      * @throws Exception
116      */
117     public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{
118         JSONObject jsonObject = null;
119         CloseableHttpClient client = null;
120         CloseableHttpResponse response = null;
121         try{
122             /**
123              *  创建一个httpclient对象
124              */
125             client = HttpClients.createDefault();
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 = client.execute(post);
150             /**
151              * 获取响应码
152              */
153             int statusCode = response.getStatusLine().getStatusCode();
154             if (SUCCESS_CODE == statusCode){
155                 /**
156                  * 通过EntityUitls获取返回内容
157                  */
158                 String result = EntityUtils.toString(response.getEntity(),"UTF-8");
159                 /**
160                  * 转换成json,根据合法性返回json或者字符串
161                  */
162                 try{
163                     jsonObject = JSONObject.parseObject(result);
164                     return jsonObject;
165                 }catch (Exception e){
166                     return result;
167                 }
168             }else{
169                 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
170             }
171         }catch (Exception e){
172             LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
173         }finally {
174             response.close();
175             client.close();
176         }
177         return null;
178     }
179 
180     /**
181      * 组织请求参数{参数名和参数值下标保持一致}
182      * @param params    参数名数组
183      * @param values    参数值数组
184      * @return 参数对象
185      */
186     public static List<NameValuePair> getParams(Object[] params, Object[] values){
187         /**
188          * 校验参数合法性
189          */
190         boolean flag = params.length>0 && values.length>0 &&  params.length == values.length;
191         if (flag){
192             List<NameValuePair> nameValuePairList = new ArrayList<>();
193             for(int i =0; i<params.length; i++){
194                 nameValuePairList.add(new BasicNameValuePair(params[i].toString(),values[i].toString()));
195             }
196             return nameValuePairList;
197         }else{
198             LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197, "请求参数为空且参数长度不一致");
199         }
200         return null;
201     }
202 }
复制代码

 3、调用方法

复制代码
 1 package com.sinotn.service.impl;
 2 
 3 import com.sinotn.service.HttpClientService;
 4 import org.apache.http.NameValuePair;
 5 
 6 import java.util.List;
 7 
 8 /**
 9  * 发送post/get 测试类
10  */
11 public class Test {
12 
13     public 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 = HttpClientService.getParams(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

复制代码
 1 import java.security.cert.CertificateException;
 2 import java.security.cert.X509Certificate;
 3 import javax.net.ssl.SSLContext;
 4 import javax.net.ssl.TrustManager;
 5 import javax.net.ssl.X509TrustManager;
 6 import org.apache.http.conn.ClientConnectionManager;
 7 import org.apache.http.conn.scheme.Scheme;
 8 import org.apache.http.conn.scheme.SchemeRegistry;
 9 import org.apache.http.conn.ssl.SSLSocketFactory;
10 import org.apache.http.impl.client.DefaultHttpClient;
11 //用于进行Https请求的HttpClient
12 public class SSLClient extends DefaultHttpClient{
13     public SSLClient() throws Exception{
14         super();
15         SSLContext ctx = SSLContext.getInstance("TLS");
16         X509TrustManager tm = new X509TrustManager() {
17                 @Override
18                 public void checkClientTrusted(X509Certificate[] chain,
19                         String authType) throws CertificateException {
20                 }
21                 @Override
22                 public void checkServerTrusted(X509Certificate[] chain,
23                         String authType) throws CertificateException {
24                 }
25                 @Override
26                 public X509Certificate[] getAcceptedIssuers() {
27                     return 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 = this.getConnectionManager();
33         SchemeRegistry sr = ccm.getSchemeRegistry();
34         sr.register(new Scheme("https", 443, ssf));
35     }
36 }
复制代码

5、对于https调用

以上是关于java 执行https的请求的主要内容,如果未能解决你的问题,请参考以下文章

暑假自学JAVA Web心得

C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段

执行带有axios的GET请求时出现401错误

java 执行https的请求

PHP代码-psysh调试代码片段工具

在 Java 的 GraphQL 查询中添加片段