一. 在实际的开发过程中,往往需要对接第三方的平台,这个时候就有两种方式去实现:1.前端直接请求第三方平台.2.在后台采用构造请求的方式去请求第三方平台.这里只记录在后台构造请求的方式,去请求第三方平台.
二.添加依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
三.下面就以请求和刷新头肯为例,说明GET和POST两种请求方式,是怎么实现构造请求的.废话不多说直接贴代码
public class CloseableHttpClientUtil {
private static CloseableHttpClient httpClient = null;
/***
* 获取token 请求方式为Get方式
* @param url 请求地址
* @param appId appId
* @param appKey appKey
* @return JSONObject
*/
public static JSONObject getToken(String url, String appId, String appKey) {
String data = "";
if (null == httpClient) {
httpClient = HttpClientBuilder.create().build();
}
HttpGet httpGet = new HttpGet(url + "/api/getToken?appId=" + appId + "&appKey=" + appKey);
httpGet.setHeader("Content-Type", "application/json");
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
return JSON.parseObject(data);
}
/**
* 刷新token POST 请求方式
*
* @param url 请求地址
* @param token 原始token
* @return
*/
public static JSONObject refreshToken(String url, String token) {
if (null == httpClient) {
httpClient = HttpClientBuilder.create().build();
}
HttpPost httpPost = new HttpPost(url + "/api/refreshToken");
//因为文档要求,刷新token时,旧的token需要存储到请求头内
httpPost.addHeader("Authorization", token);
httpPost.addHeader("Content-Type", "application/json");
try {
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String res = EntityUtils.toString(response.getEntity());
return JSON.parseObject(res);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static void main(String[] args) {
String url = "http://127.0.0.1:8888";
String appId = "123456";
String appKey = "123456";
JSONObject token = getToken(url, appId, appKey);
} }
本文介绍了一种通过在后台构造HTTP请求来与第三方平台交互的方法,包括使用GET和POST请求获取和刷新token的具体实现。


被折叠的 条评论
为什么被折叠?



