• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

无信不立

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

【HttpClient】协议

https://blog.csdn.net/weixin_40918067/article/details/116615033

 

maven坐标

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

代码块

import lombok.Data;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.cookie.Cookie;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.util.List;

/**

 */
public class HttpClientUtil {
    //从连接池获取连接的超时时间(单位毫秒)
    private static final int CONNECTION_REQUEST_TIMEOUT = 5000;
    //与服务器连接的超时时间(单位毫秒)
    private static final int CONNECTION_TIMEOUT = 5000;
    //从服务器获取相应数据超时时间(单位毫秒)
    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 CloseableHttpClient httpClient;

    public HttpClientUtil() {
        ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build();
        SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        BasicCookieStore basicCookieStore = new BasicCookieStore();
        this.httpClient = HttpClients.custom().setDefaultConnectionConfig(connectionConfig).setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(requestConfig).setDefaultCookieStore(basicCookieStore).setMaxConnTotal(MAX_CONN_TOTAL).setMaxConnPerRoute(MAX_CONN_PER_ROUTE).build();
    }


    public HttpResult sendPostJson(String url, String jsonData, String charset, Header[] headers, Cookie[] cookies) {
        try {
            HttpPost httpPost = new HttpPost(url);
            if (headers != null) {
                httpPost.setHeaders(headers);
            }
            if (cookies != null) {
                StringBuilder sb = new StringBuilder();
                for (Cookie cookie : cookies) {
                    sb.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
                }
                httpPost.setHeader("cookie", sb.toString());
            }
            if (jsonData == null || "".equals(jsonData)) {
                jsonData = "{}";
            }
            StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);
            if (charset != null) {
                stringEntity.setContentEncoding(charset);
            }
            return this.httpClient.execute(httpPost, httpResponse -> {
                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());
                httpResult.setTextType(isTextType(contentType));
                if(httpResult.isTextType()){
                    httpResult.setRespResult(EntityUtils.toString(httpEntity));
                }else{
                    httpResult.setRespByteResult(EntityUtils.toByteArray(httpEntity));
                }
                httpResult.setHeaders(httpResponse.getAllHeaders());
                return httpResult;
            });
        } catch (Exception e) {
            throw new RuntimeException("网络请求异常", e);
        }
    }

    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;
        }
    }

    public void destroy() {

        if (this.httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            this.httpClient = null;
        }
    }


    @Data
    public static class HttpResult {
        private Header[] headers;
        private List<Cookie> cookieList;
        private int statusCode;
        private String contentType;
        private boolean isTextType;
        private String respResult;
        private byte[] respByteResult;
    }
}
View Code

 

posted on 2024-02-21 22:33  无信不立  阅读(9)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3