Java调用第三方http或https接口的方式
1.概述
1.在实际开发中我们经常会与第三方公司进行合作,接入第三方接口;在Java项目中调用第三方接口的方式有:
①通过JDK网络类Java.net.HttpURLConnection;
②通过Apache common封装好的HttpClient;
③通过Apache封装好的CloseableHttpClient;
④通过SpringBoot的RestTemplate;
参考链接:https://www.cnblogs.com/swordfall/p/10757499.html
2.具体实现
2.1通过JDK网络类Java.net.HttpURLConnection
package com.example.demo1.domain;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @Author: HongZhi Wang
* @Date: 2020/8/12 16:35
*
* jdk的HttpURLConnection类调用第三方http接口
* 通常分get和post两种方式
*
*/
public class HttpURLConnectionDemo {
public static void doPost(String pathUrl,String data) {
OutputStreamWriter out = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try {
//1.创建URL对象
URL url = new URL(pathUrl);
//2.建立连接,获取HttpURLConnection对象
HttpURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
//3.设置请求方式
httpURLConnection.setRequestMethod("GET");//需要全部大写
//httpURLConnection.setRequestMethod("POST");
//4.设置请求头信息
httpURLConnection.setRequestProperty("accept","*/*");
httpURLConnection.setRequestProperty("connection","Keep-Alive");
//httpURLConnection.setRequestProperty("authToken","12345");//可设置token
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
httpURLConnection.setRequestProperty("Content-Type","application/json;charset=utf-8");
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入(post请求必须设置这两个)
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//5.获取URLConnection对象对应的输出流(调用)
out = new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8");
out.write(data);//携带参数请求第三方接口
out.flush();
//6.处理第三方http接口后返回的结果
InputStream is = httpURLConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
result.append(str);
}
is.close();
System.out.println(result.toString());
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
httpURLConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.2通过apache common封装好的HttpClient
httpClient的get或post请求方式步骤:
1.生成一个HttpClient对象并设置相应的参数;
2.生成一个GetMethod对象或PostMethod并设置响应的参数;
3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
4.处理响应状态码;
5.若响应正常,处理HTTP响应内容;
6.释放连接。
导入jar包:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
代码如下:
package com.example.demo1.domain;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.IOException;
/**
* @Author: HongZhi Wang
* @Date: 2020/8/13 19:24
*/
public class HttpClientDemo {
public static void doGet(String url){
//1.生成一个HttpClient对象并设置相应的参数;
HttpClient httpClient = new HttpClient();
//设置http连接超时时间为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
//2.生成一个GetMethod对象或PostMethod并设置响应的参数;
GetMethod getMethod = new GetMethod(url);
//设置get请求超时时间为5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
//3.执行请求
try {
int statusCode = httpClient.executeMethod(getMethod);
//4.处理响应状态码;
if (statusCode == HttpStatus.SC_OK){
System.out.println("请求结果:" + getMethod.getResponseBodyAsString());
} else {
System.err.println("请求出错:" + getMethod.getStatusLine());
}
//5.若响应正常,处理HTTP响应内容;
//HTTP响应头部信息,这里简单打印
Header[] headers = getMethod.getResponseHeaders();
for (Header h: headers){
System.out.println(h.getName() + "===============" + h.getValue());
}
//读取HTTP响应内容,这里简单打印网页内容
//读取为字节数组
byte[] responseBody = getMethod.getResponseBody();
String response = new String(responseBody, "GBK");
System.out.println("=============response:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
/**
* 6.释放连接
*/
getMethod.releaseConnection();
}
}
public static void doPost(String url, JSONObject jsonObject){
//1.生成一个HttpClient对象并设置相应的参数;
HttpClient httpClient = new HttpClient();
//设置http连接超时时间为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
//2.生成一个GetMethod对象或PostMethod并设置响应的参数;
PostMethod postMethod = new PostMethod(url);
//设置get请求超时时间为5秒
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
//设置请求头header信息
postMethod.addRequestHeader("accept","*/*");
postMethod.addRequestHeader("connection","Keep-Alive");
postMethod.addRequestHeader("Content-Type","application/json;charset=utf-8");
//必须设置下面这个Header
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//可自定义添加请求参数
//postMethod.addParameter("commentId", jsonObject.getString("commentId"));
//postMethod.addParameter("authToken", jsonObject.getString("authToken"));
//3.执行请求
try {
int statusCode = httpClient.executeMethod(postMethod);
//4.处理响应状态码;
if (statusCode == HttpStatus.SC_OK){
System.out.println("请求结果:" + postMethod.getResponseBodyAsString());
} else {
System.err.println("请求出错:" + postMethod.getStatusLine());
}
//5.若响应正常,处理HTTP响应内容;
//HTTP响应头部信息,这里简单打印
Header[] headers = postMethod.getResponseHeaders();
for (Header h: headers){
System.out.println(h.getName() + "===============" + h.getValue());
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
/**
* 6.释放连接
*/
postMethod.releaseConnection();
}
}
}
2.3通过Apache封装好的CloseableHttpClient
CloseableHttpClient是在HttpClient的基础上修改更新而来的。
导入jar包:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
代码如下:
package com.example.demo1.domain;
import com.alibaba.fastjson.JSONObject;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.util.Objects;
/**
* @Author: HongZhi Wang
* @Date: 2020/8/14 13:40
*/
public class CloseableHttpClientDemo {
private static String tokenString = "";
/**
* 以get方式调用第三方接口
*/
public static String doGet(String url,boolean isHttps) {
String responseContent = "";
//1.创建HttpClient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
//这里我加了一个是否需要创建一个https连接的判断
if (isHttps) {
//配置https请求的一些参数
SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
} else {
httpClient = HttpClientBuilder.create().build();
}
//2.生成get请求对象,并设置请求头信息
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("auth_token", tokenString);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//3.执行请求
response = httpClient.execute(httpGet);
//4.处理响应信息
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(response.getEntity(),"utf-8");
return responseContent;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 以post方式调用第三方接口
*/
public static String doPost(String url, boolean isHttps, JSONObject paramEntity) {
String responseContent = "";
//1.创建HttpClient对象
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
if (isHttps) {
//配置https请求的一些参数
SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
} else {
httpClient = HttpClientBuilder.create().build();
}
//2.生成post请求对象,并设置请求头信息
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("auth_token", tokenString);
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//3.设置请求参数
if (!Objects.isNull(paramEntity)) {
String paramStr = JSONObject.toJSONString(paramEntity);
StringEntity entity = new StringEntity(paramStr,ContentType.create("application/json","utf-8"));
httpPost.setEntity(entity);
}
//4.执行请求
response = httpClient.execute(httpPost);
//5.处理响应信息
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(response.getEntity(),"utf-8");
return responseContent;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
}
2.4通过SpringBoot的RestTemplate
- exchange() 方法,执行指定的URL请求, 返回一个 ResponseEntity 对象, 这个对象是从响应体映射而来。
- getForEntity() 方法, 发送一个 GET 请求, 返回一个ResponseEntity 对象,返回的ResponseEntity包含了响应体所映射成的对象。
- getForObject() 方法,发送一个 GET 请求, 返回一个 pojo 对象。
- PostForEntity() 方法,发送一个 Post 请求, 返回一个 ResponseEntity 对象,返回的ResponseEntity包含了响应体所映射成的对象。
- PostForObject() 方法,发送一个 POST 请求, 返回一个 pojo 对象。
- PostForLocation() 方法, POST 数据到一个URL,返回新创建资源的URL。
- delete() 方法,删除指定URI处的资源。
- execute() 方法,执行指定URL的HTTP方法,返回一个从响应体映射得到的对象。
- headForHeaders() 方法,发送HTTP HEAD请求,返回包含特定资源URL的HTTP头。
- optionsForAllow() 方法,发送HTTP OPTIONS请求,返回对特定URL的Allow头信息。
- put() 方法,发送 PUT 请求。
代码如下:
1.需要导入springboot相关jar包 。
2. 在启动类同包下创建RestTemplateConfig.java类(参考链接:https://blog.youkuaiyun.com/qq_31491785/article/details/80249917)
package com.example.demo1;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @Author: HongZhi Wang
* @Date: 2020/8/17 16:45
*
* 创建RestTemplate配置类,设置连接池大小、超时时间、重试机制等。
*/
@Configuration
@Slf4j
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(clientHttpRequestFactory());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
return restTemplate;
}
@Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
try {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
httpClientBuilder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build(); //注册http和https请求
//开始设置连接池
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); //创建连接池
poolingHttpClientConnectionManager.setMaxTotal(500); // 最大连接数500
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100); // 同路由并发数100
httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); // 重试次数
HttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // httpClient连接配置
clientHttpRequestFactory.setConnectTimeout(20000); // 连接超时
clientHttpRequestFactory.setReadTimeout(30000); // 数据读取超时时间
clientHttpRequestFactory.setConnectionRequestTimeout(20000); // 连接不够用的等待时间
return clientHttpRequestFactory;
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("初始化HTTP连接池出错", e);
}
return null;
}
}
- 在Service类中注入使用
package com.example.demo1.service;
import com.alibaba.fastjson.JSONObject;
import com.example.demo1.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* @Author: HongZhi Wang
* @Date: 2020/8/17 17:52
*/
@Service
@Slf4j
public class RestTemplateTest {
@Autowired
private RestTemplate restTemplate;
/**
* 以get方式请求第三方http接口 getForEntity
* @param url
* @return
*/
public JSONObject doGetForEntity(String url) {
ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(url, JSONObject.class);
return responseEntity.getBody();
}
/**
* 以get方式请求第三方http接口 getForObject
* 返回值返回的是响应体
* @param url
* @return
*/
public JSONObject doGetForObject(String url) {
JSONObject result = restTemplate.getForObject(url, JSONObject.class);
return result;
}
/**
* 以post方式请求第三方http接口 postForEntity
* @param url
* @return
*/
public JSONObject doPostForEntity(String url) {
//可设置请求参数
JSONObject param = new JSONObject();
param.put("auth_token","12345");
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, param, JSONObject.class);
return responseEntity.getBody();
}
/**
* 以post方式请求第三方http接口 postForObject
* @param url
* @return
*/
public JSONObject doPostForObject(String url) {
//可设置请求参数
JSONObject param = new JSONObject();
param.put("auth_token","12345");
JSONObject result = restTemplate.postForObject(url, param, JSONObject.class);
return result;
}
/**
* exchange方法请求第三方http接口
*
*/
public JSONObject doExchange(String url,String token) {
//设置header中参数
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("auth_token",token);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//设置请求参数
JSONObject param = new JSONObject();
param.put("auth_token",token);
//创建请求对象
HttpEntity<JSONObject> request = new HttpEntity<>(param,httpHeaders);
//执行请求(请求路径,请求方式,请求体,响应体)
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class);
return responseEntity.getBody();
}
}