java 使用 Apache HttpClient 发送带参数的POST、GET、PUT、DELETE请求,并且配置 Cookie

pom

  <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.13</version>
  </dependency>

测试代码

替换下面这个对象的构造方法即可
BasicClientCookie cookie = new BasicClientCookie()

package common;

import com.dstz.base.api.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Lisy
 * @Date: 2023/03/10/16:57
 * @Description: restfull 接口调用测试类
 */
@Slf4j
public class TestHttpClient {

    /**
     *
     * @param url http://127.0.0.1:8089/getRoot
     * @param parameter "name:张三;age:18";
     * @param timeout 超时时间 10000 毫秒
     * @param requestType  // 0-GET 1-POST 2-PUT 3-DELETE
     * @param contentType 0-application/x-www-form-urlencoded,1-application/json
     * @return 接口调用结果
     */
    private String getInterfaceTestResult(String url, String parameter,
                                          Integer timeout, Integer requestType, Integer contentType) {
        List<NameValuePair> params = getNameValuePairs(parameter);
        // cookie 设置
        BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("Authorization", "Bearer-eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJhZ2lsZUJQTSIsInN1YiI6ImRybWFkbWluIiwiYXVkIjoicGMiLCJpYXQiOjE2Nzg0MzE2Njh9.x7_tTO02sskkjrx-EKrphUoTL1iCtIxgHqnYTzMpyqBTIkzWGAJ0cePeE_Ux_iQZDvyqPxgMIvK5_k0Da9ddng");
        cookie.setPath("/");
        cookie.setDomain(getDomain(url));
        cookieStore.addCookie(cookie);

        HttpUriRequest httpRequest;
        try (CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(getRequestConfig(timeout))
                .setDefaultCookieStore(cookieStore).build()) {
            // 0-GET 1-POST 2-PUT 3-DELETE
            switch (requestType) {
                case 0:
                    HttpGet httpGet = new HttpGet(url);
                    processGetAndDelete(url, params, httpGet);
                    httpRequest = httpGet;
                    break;
                case 3:
                    HttpDelete httpDelete = new HttpDelete(url);
                    processGetAndDelete(url, params, httpDelete);
                    httpRequest = httpDelete;
                    break;
                case 1:
                    HttpPost httpPost = new HttpPost(url);
                    processPutAndPost(contentType, params, httpPost, parameter);
                    httpRequest = httpPost;
                    break;
                case 2:
                    HttpPut httpPut = new HttpPut(url);
                    processPutAndPost(contentType, params, httpPut, parameter);
                    httpRequest = httpPut;
                    break;

                default:
                    throw new IllegalStateException("Unknown request type: " + requestType);
            }

            // 处理结果
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest, HttpClientContext.create())) {
                HttpEntity httpEntity = httpResponse.getEntity();
                return EntityUtils.toString(httpEntity, StandardCharsets.UTF_8);
            } catch (Exception e) {
                throw new BusinessException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取domain
     * http://localhost:8999/getRoot
     * http://127.0.0.1:8089/getRoot
     * https://xc.com
     *
     * @param rootUrl 根路径
     * @return 返回cookie domain
     */
    private String getDomain(String rootUrl) {
        String[] split = rootUrl.split("//");
        if (split.length < 2) {
            throw new IllegalArgumentException("根路径不符合规范:" + rootUrl);
        }

        String s = split[1];
        String result;
        if (s.contains(":")) {
            // 127.0.0.1:8089
            String[] tmp = s.split(":");
            if (tmp.length < 1) {
                throw new IllegalArgumentException("根路径不符合规范:" + rootUrl);
            }
            result = tmp[0];
        } else {
            // xc.com
            if (s.contains("/")) {
                String[] tmp = s.split("/");
                if (tmp.length == 2 && StringUtils.isNotBlank(tmp[0])) {
                    result = tmp[0];
                } else {
                    throw new IllegalArgumentException("根路径不符合规范:" + rootUrl);
                }
            } else {
                result = s;
            }
        }
        return result;
    }

    private void processGetAndDelete(String testUrl, List<NameValuePair> params, HttpRequestBase httpRequestBase) {
        String paramString = URLEncodedUtils.format(params, StandardCharsets.UTF_8);
        // 配置信息
        httpRequestBase.setURI(URI.create(testUrl + "?" + paramString));
    }

    private void processPutAndPost(Integer contentType, List<NameValuePair> params,
                                   HttpEntityEnclosingRequestBase httpBase, String parameter) {
        HttpEntity putEntity;
        String putType;
        if (contentType.equals(0)) {
            putEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
            putType = "application/x-www-form-urlencoded";
        } else {
            String par = getJsonParam(parameter);
            putEntity = new StringEntity(par, ContentType.APPLICATION_JSON);
            putType = "application/json";
        }
        httpBase.setEntity(putEntity);
        httpBase.addHeader(HttpHeaders.CONTENT_TYPE, putType);
    }

    /**
     * 设置超时时间
     *
     * @param timeout 超时时间
     * @return RequestConfig 超时时间
     */
    private RequestConfig getRequestConfig(Integer timeout) {
        return RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(timeout)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(timeout)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(timeout)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
    }

    /**
     * 处理跟路径与附属路径有关 '/' 的处理
     *
     * @param secondUrl 第二路径 /getall
     * @param rootUrl   跟路径 www.example.com
     * @return 根路径与第二路径拼接参数 www.example.com/getall
     */
    private String getTestUrl(String secondUrl, String rootUrl) {
        int length = rootUrl.length() - 1;
        // 去除根路径末尾的 /
        if (rootUrl.lastIndexOf("/") == length) {
            rootUrl = rootUrl.substring(0, rootUrl.length() - 1);
        }
        // 判断第二路径头部分是否以 / 开头,并完成拼接
        String substring = secondUrl.substring(0, 1);
        if ("/".equals(substring)) {
            rootUrl += substring;
        } else {
            rootUrl += "/" + secondUrl;
        }
        return rootUrl;
    }

    /**
     * 获取JSON形式的字符串
     *
     * @param parameter "name:张三;age:18";
     * @return {"name":"张三","age":"18"}
     */
    private String getJsonParam(String parameter) {
        String[] split = parameter.split(";");
        List<String> collect = Arrays.stream(split).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder("{");
        collect.forEach(key -> {
            String[] kv = key.split(":");
            sb.append("\"").append(kv[0]).append("\":\"").append(kv[1]).append("\"").append(",");
        });
        sb.deleteCharAt(sb.length() - 1);
        sb.append("}");
        return sb.toString();
    }

    /**
     * 返回 application/x-www-form-urlencoded 所需要的参数
     *
     * @param parameter "name:张三;age:18";
     * @return NameValuePair 集合
     */
    private List<NameValuePair> getNameValuePairs(String parameter) {
        String[] split = parameter.split(";");
        List<String> collect = Arrays.stream(split).collect(Collectors.toList());
        List<NameValuePair> params = new LinkedList<>();
        collect.forEach(key -> {
            String[] kv = key.split(":");
            params.add(new BasicNameValuePair(kv[0], kv[1]));
        });
        return params;
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的HttpClient是一个开源的HTTP客户端库,用于发送HTTP请求和处理HTTP响应。它提供了丰富的功能和灵活的API,可以用于构建各种类型的HTTP请求,包括GETPOSTPUTDELETE等。HttpClient可以与各种HTTP服务器进行通信,并支持处理各种HTTP协议相关的功能,例如设置请求头、处理cookie、处理重定向等。 在Java使用HttpClient发送HTTP请求的一个例子如下: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com/api/users"); CloseableHttpResponse response = null; try { response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println("content = " + content); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) response.close(); if (httpClient != null) httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 上述代码演示了使用HttpClient发送一个GET请求并输出响应内容。 除了上述的基本用法外,HttpClient还提供了一些封装工具方法,例如doGet、doPost、doPostJson等,可以简化HTTP请求的编写过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值