Java发送POST和GET请求

本文详细描述了如何使用ApacheHttpClient库在Java中发送POST和GET请求到RESTful接口,包括设置请求头、参数、超时和异常处理。
摘要由CSDN通过智能技术生成

最近因业务需求需要从其他系统提供的RESTful接口获取数据,涉及到POST请求和GET请求,这里采用Java实现。

引入依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>

发送POST请求


protected JSONObject doPost(String url, String token, JSONObject json) {
    long t = new Date().getTime();
    String newUrl = String.format("%s?_t=%s", url, t);
    try {
        RequestConfig.custom().setConnectionRequestTimeout(3000).setSocketTimeout(3000).setConnectTimeout(3000).build();
        // 创建Get请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.addHeader("Connection", "keep-alive");
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        if (!StringUtils.isNotBlank(token)) {
            httpPost.addHeader("token", token);
        }
        // httpPost.addHeader("Host", "pan.baidu.com");
        // httpPost.addHeader("Origin", "https://pan.baidu.com");
        // httpPost.addHeader("Referer", String.format("https://pan.baidu.com/share/init?surl=%s", id));
        // Post参数
        // List<NameValuePair> params = new ArrayList<>();
        // params.add(new BasicNameValuePair("pwd", code));
        // params.add(new BasicNameValuePair("vcode", ""));
        // params.add(new BasicNameValuePair("vcode_str", ""));
        // httpPost.setEntity(new UrlEncodedFormEntity(params, charset));

        // 设置参数编码格式,如果不用Charset.forName("UTF-8"),服务端中文乱码
        StringEntity entityRequest = new StringEntity(json.toString(), Charset.forName("UTF-8"));
        // 设置参数格式为json
        entityRequest.setContentType("application/json");
        // GET请求的参数
        httpPost.setEntity(entityRequest);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entityResponse = response.getEntity();
        String responseContent = EntityUtils.toString(entityResponse, charset);
        log.debug(responseContent);
        response.close();
        httpClient.close();
        JSONObject jsonResponse = JSON.parseObject(responseContent);
        return jsonResponse;
    } catch (Exception e) {
        log.error("{}.doPost throw exception: {}", this.getClass().getSimpleName(), e.getMessage());
    }
    return null;
}

发送GET请求

protected JSONObject doGet(String url, String token, String cookie) {
    long t = new Date().getTime();
    String newUrl = String.format("%s?_t=%s", url, t);
    try {
        RequestConfig.custom().setConnectionRequestTimeout(3000).setSocketTimeout(3000).setConnectTimeout(3000).build();
        // 创建Get请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet http = new HttpGet(url);
        http.setHeader("token", token);
        CloseableHttpResponse response = httpClient.execute(http);
        HttpEntity entityResponse = response.getEntity();
        String responseContent = EntityUtils.toString(entityResponse, charset);
        log.debug(responseContent);
        response.close();
        httpClient.close();
        JSONObject jsonResponse = JSON.parseObject(responseContent);
        return jsonResponse;
    } catch (Exception e) {
        log.error("{}.doGet throw exception: {}", this.getClass().getSimpleName(), e.getMessage());
    }
    return null;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

angushine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值