java 构建http请求的方法

java 构建http请求的方法,第1张

java 构建http请求的方法

一. 在实际的开发过程中,往往需要对接第三方的平台,这个时候就有两种方式去实现:1.前端直接请求第三方平台.2.在后台采用构造请求的方式去请求第三方平台.这里只记录在后台构造请求的方式,去请求第三方平台.

二.添加依赖:


    org.apache.httpcomponents
    httpclient
    4.5.2

    com.alibaba
    fastjson
    1.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);
}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5079003.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存