一. 在实际的开发过程中,往往需要对接第三方的平台,这个时候就有两种方式去实现:1.前端直接请求第三方平台.2.在后台采用构造请求的方式去请求第三方平台.这里只记录在后台构造请求的方式,去请求第三方平台.
二.添加依赖:
org.apache.httpcomponents httpclient4.5.2
com.alibaba fastjson1.2.32
三.下面就以请求和刷新头肯为例,说明GET和POST两种请求方式,是怎么实现构造请求的.废话不多说直接贴代码
public class CloseableHttpClientUtil { private static CloseableHttpClient httpClient = null;
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); } 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);
} }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)