java通过 httpclient 发送post/get/存储cookies

<!-- http -->
<dependency>
	<groupId>com.github.kevinsawicki</groupId>
	<artifactId>http-request</artifactId>
	<version>5.6</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpcore</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
</dependency>
package com.zhichenhaixin.util;

/**
 * HttpClient发送Get请求和Post请求的封装类
 */
public class HttpClientUtil {
    private static final Logger log = Logger.getLogger(HttpClientUtil.class);
    /**
     * 从连接池中获取连接的超时时间(单位:ms)
     */
    private static final int CONNECTION_REQUEST_TIMEOUT = 5000;

    /**
     * 与服务器连接的超时时间(单位:ms)
     */
    private static final int CONNECTION_TIMEOUT = 5000;

    /**
     * 从服务器获取响应数据的超时时间(单位:ms)
     */
    private static final int SOCKET_TIMEOUT = 10000;

    /**
     * 连接池的最大连接数
     */
    private static final int MAX_CONN_TOTAL = 100;

    /**
     * 每个路由上的最大连接数
     */
    private static final int MAX_CONN_PER_ROUTE = 50;

    /**
     * 用户代理配置
     */
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36";

    /**
     * HttpClient对象
     */
    private static CloseableHttpClient httpClient = null;

    /**
     * Connection配置对象
     */
    private static ConnectionConfig connectionConfig = null;

    /**
     * Socket配置对象
     */
    private static SocketConfig socketConfig = null;

    /**
     * Request配置对象
     */
    private static RequestConfig requestConfig = null;

    /**
     * Cookie存储对象
     */
    private static BasicCookieStore cookieStore = null;
    private static PoolingHttpClientConnectionManager cm;

    static {
        init();
    }

    /**
     * 全局对象初始化
     */
    private static void init() {
        // 创建Connection配置对象
        connectionConfig = ConnectionConfig.custom()
                .setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE)
                .setCharset(Consts.UTF_8).build();

        // 创建Socket配置对象
        socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();

        // 创建Request配置对象
        requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .build();
        // 创建Cookie存储对象(服务端返回的Cookie保存在CookieStore中,下次再访问时才会将CookieStore中的Cookie发送给服务端)
        cookieStore = new BasicCookieStore();

        // 创建HttpClient对象
        httpClient = HttpClients.custom()
                .setMaxConnTotal(50)
                .setDefaultConnectionConfig(connectionConfig)
                .setDefaultSocketConfig(socketConfig)
                .setDefaultRequestConfig(requestConfig)
                .setDefaultCookieStore(cookieStore)
                .setUserAgent(USER_AGENT)
                .setMaxConnTotal(MAX_CONN_TOTAL)
                .setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
                .setConnectionManagerShared(true)
                .build();
    }

    public static HttpResult sendGet(String url, Cookie[] cookies) {
        return sendGet(url, null, null, cookies, null);
    }

    /**
     * 发送Get请求
     *
     * @param url        请求的地址
     * @param parameters 请求的数据
     * @param cookies    请求的Cookie信息
     * @param headers    请求的头部信息
     * @param charset    请求数据的字符编码
     */
    public static HttpResult sendGet(String url, Map<String, String> parameters, Header[] headers, Cookie[] cookies, String charset) {
        HttpResult httpResult = null;
        try {
            // 创建URI并设置参数
            URIBuilder builder = new URIBuilder(url);
            if (parameters != null && !parameters.isEmpty()) {
                builder.addParameters(assemblyParameter(parameters));
            }
            if (charset != null) {
                builder.setCharset(Charset.forName(charset));
            }
            URI uri = builder.build();

            // 创建HttpGet
            headers = new Header[2];
            HttpGet httpGet = new HttpGet(uri);
            headers[0] = new BasicHeader("Content-Type", "text/xml");
            headers[1] = new BasicHeader("Accept-Ranges", "bytes");
            // 设置Header
            if (headers != null) {
                /**
                 * httpGet.setHeaders(headers),重新设置Header,前面set或者add的Header都会被去掉
                 * httpGet.setHeader(header):如果已经有了同名的Header,则覆盖同名的Header,如果没有,则添加Header
                 * httpGet.addHeader(header):不管是否已经有了同名的Header,都添加Header,可能会导致存在同名的Header
                 */

                httpGet.setHeaders(headers);

            }
            // 设置Cookie
            if (cookies != null) {
                /**
                 * Cookie必须通过Header来设置
                 */
                httpGet.setHeader("cookie", assemblyCookie(cookies));
            }
            // 发送Post请求并得到响应结果
            httpResult = httpClient.execute(httpGet, getResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpResult;
    }

    /**
     * 发送Post请求(Form格式的数据)
     *
     * @param url        请求的地址
     * @param parameters 请求的Form数据
     * @param cookies    请求的Cookie信息
     * @param headers    请求的头部信息
     * @param charset    请求数据的字符编码
     */
    public static HttpResult sendPostForm(String url, Map<String, String> parameters, Header[] headers, Cookie[] cookies, String charset) {
        HttpResult httpResult = null;
        try {
            // 创建HttpPost
            HttpPost httpPost = new HttpPost(url);

            // 设置请求数据
            if (parameters != null && !parameters.isEmpty()) {
                httpPost.setEntity(assemblyFormEntity(parameters, charset));
            }

            // 设置Header
            if (headers != null) {

                httpPost.setHeaders(headers);
            }
            // 发送Post请求并得到响应结果
            httpResult = httpClient.execute(httpPost, getResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpResult;
    }

    public static HttpResult sendPostFrom(String url, String jsonData) {
        HttpResult httpResult = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置Header
            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
//            httpPost.addHeader("Cookie", "loginname=;td=;");
            httpPost.addHeader("accept", "*/*");
            httpPost.addHeader("connection", "Keep-Alive");
            // 设置请求数据
            httpPost.setEntity(assemblyStringEntity(jsonData, Charset.forName("UTF-8")));
            // 发送Post请求并得到响应结果
            httpResult = httpClient.execute(httpPost, getResponseHandler());
        } catch (IOException e) {
            log.error("请求语音中心登录获取cookies失败" + e);
        }
        return httpResult;
    }

    /**
     * 发送Post请求(Json格式的数据)
     *
     * @param url      请求的地址
     * @param jsonData 请求的Json数据
     */
    public static HttpResult sendPostJson(String url, String jsonData) {
//        log.info("send url : " + url + "; send param : " + jsonData);
        HttpResult httpResult = null;
        try {
            // 创建HttpPost
            HttpPost httpPost = new HttpPost(url);
            // 设置Header
            httpPost.addHeader("Content-type", "application/json;charset=utf-8");
            httpPost.addHeader("accept", "*/*");
            httpPost.addHeader("connection", "Keep-Alive");
            // 设置请求数据
            httpPost.setEntity(assemblyStringEntity(jsonData, Charset.forName("UTF-8")));
            // 发送Post请求并得到响应结果
            httpResult = httpClient.execute(httpPost, getResponseHandler());
            // 失败以后重新登录
//            executeError(httpResult, url, jsonData);
        } catch (Exception e) {
            log.error("send url : " + url + "; send param : " + jsonData);
            e.printStackTrace();
        }
        return httpResult;
    }

    private static int i = 0;

    private static void executeError(HttpResult httpResult, String url, String jsonData) {
        YeaRespVo yeaRespVo = JSON.parseObject(httpResult.getStringContent(), YeaRespVo.class);
        if (httpResult.getStringContent() == null || !yeaRespVo.getStatus().equals("Success") || yeaRespVo.getErrno().equals("20004")) {
            if (i < 10) {
                YeastarConstant.yeastarToken = YeastarUtils.login();
                sendPostJson(url, jsonData);
                i++;
                log.info("重新登录,token 为:" + YeastarConstant.yeastarToken);
            }
            else {
                log.error("获取token失败,请检查原因:" );
            }
        }
    }

    /**
     * 获取响应结果处理器(把响应结果封装成HttpResult对象)
     */
    private static ResponseHandler<HttpResult> getResponseHandler() {
        ResponseHandler<HttpResult> responseHandler = new ResponseHandler<HttpResult>() {
            @Override
            public HttpResult handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                if (httpResponse == null) {
                    throw new ClientProtocolException("HttpResponse is null");
                }
                StatusLine statusLine = httpResponse.getStatusLine();
                HttpEntity httpEntity = httpResponse.getEntity();
                if (statusLine == null) {
                    throw new ClientProtocolException("HttpResponse contains no StatusLine");
                }
                if (statusLine.getStatusCode() != 200) {
                    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
                }
                if (httpEntity == null) {
                    throw new ClientProtocolException("HttpResponse contains no HttpEntity");
                }

                HttpResult httpResult = new HttpResult();
                httpResult.setStatusCode(statusLine.getStatusCode());
                ContentType contentType = ContentType.getOrDefault(httpEntity);
                httpResult.setContentType(contentType.toString());
                boolean isTextType = isTextType(contentType);
                httpResult.setTextType(isTextType);
                if (isTextType) {
                    httpResult.setStringContent(EntityUtils.toString(httpEntity));
                } else {
                    httpResult.setByteArrayContent(EntityUtils.toByteArray(httpEntity));
                }
                httpResult.setCookies(cookieStore.getCookies());
                httpResult.setHeaders(httpResponse.getAllHeaders());

                return httpResult;
            }
        };
        return responseHandler;
    }

    /**
     * 组装Get请求的请求参数
     *
     * @param parameters 参数信息集合
     */
    private static List<NameValuePair> assemblyParameter(Map<String, String> parameters) {
        List<NameValuePair> allParameter = new ArrayList<>();
        if (parameters != null && !parameters.isEmpty()) {
            for (String name : parameters.keySet()) {
                NameValuePair parameter = new BasicNameValuePair(name, parameters.get(name));
                allParameter.add(parameter);
            }
        }
        return allParameter;
    }

    /**
     * 组装Post请求的Form请求体
     *
     * @param parameters 请求的表单参数
     * @param charset    请求参数的字符编码
     */
    private static UrlEncodedFormEntity assemblyFormEntity(Map<String, String> parameters, String charset) {
        List<NameValuePair> formParameters = assemblyParameter(parameters);
        UrlEncodedFormEntity formEntity = null;
        try {
            if (charset != null) {
                formEntity = new UrlEncodedFormEntity(formParameters, charset);
            } else {
                formEntity = new UrlEncodedFormEntity(formParameters);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return formEntity;
    }

    /**
     * 组装Post请求的Json请求体
     *
     * @param jsonData 请求的Json数据
     * @param charset  请求参数的字符编码
     */
    private static StringEntity assemblyStringEntity(String jsonData, Charset charset) {
        /**
         * jsonData不能为null和"",否则无法创建StringEntity。
         * Json类型的请求体,必须传一个不为null的StringEntity给服务端。
         * 如果jsonData为null或""时,则进行特殊处理。
         */
        if (jsonData == null || jsonData.equals("")) {
            jsonData = "{}";
        }
        StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);
        if (charset != null) {
            stringEntity.setContentEncoding("UTF-8");
        }
        return stringEntity;
    }

    /**
     * 组装Cookie
     *
     * @param cookies 所有的Cookie数据
     */
    private static String assemblyCookie(Cookie[] cookies) {
        StringBuilder sb = new StringBuilder();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                sb.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
            }
        }
        return sb.toString();
    }

    /**
     * 判断响应的内容是否是文本类型
     *
     * @param contentType 响应内容的类型
     */
    private static boolean isTextType(ContentType contentType) {
        if (contentType == null) {
            throw new RuntimeException("ContentType is null");
        }
        if (contentType.getMimeType().startsWith("text")) {
            return true;
        } else if (contentType.getMimeType().startsWith("image")) {
            return false;
        } else if (contentType.getMimeType().startsWith("application")) {
            if (contentType.getMimeType().contains("json") || contentType.getMimeType().contains("xml")) {
                return true;
            } else {
                return false;
            }
        } else if (contentType.getMimeType().startsWith("multipart")) {
            return false;
        } else {
            return true;
        }
    }

}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个使用HttpClient发送Post请求并携带cookie的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; public class HttpClientUtil { public static void main(String[] args) throws Exception { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建CookieStore实例 CookieStore cookieStore = new BasicCookieStore(); // 创建HttpPost实例 HttpPost httpPost = new HttpPost("http://example.com/login"); // 设置请求参数 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); // 设置请求头 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置请求体参数 List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("username", "example")); parameters.add(new BasicNameValuePair("password", "password")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); httpPost.setEntity(formEntity); // 执行HttpPost请求 HttpResponse httpResponse = httpClient.execute(httpPost); // 获取响应实体 HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } // 获取Cookie List<Cookie> cookies = cookieStore.getCookies(); // 创建HttpPost实例 httpPost = new HttpPost("http://example.com/data"); // 设置请求参数 requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); // 设置请求头 httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("Accept", "application/json"); // 设置请求体参数 String requestBody = "{\"key\":\"value\"}"; httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); // 设置Cookie httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); // 执行HttpPost请求 httpResponse = httpClient.execute(httpPost); // 获取响应实体 httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值