本文介绍: 【代码java 使用 Apache HttpClient 发送参数的POST、GET、PUT、DELETE请求,并且配置 Cookie

pom

  <dependency&gt;
     <groupId&gt;org.apache.httpcomponents</groupId&gt;
     <artifactId&gt;httpclient</artifactId&gt;
     <version&gt;4.5.13</version&gt;
  </dependency&gt;

测试代码

替换下面这个对象构造方法即可
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 &amp;&amp; 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;
    }
}

原文地址:https://blog.csdn.net/qq_40965479/article/details/129446684

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_12705.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注