HttpClient长连接使用

时间:2025-05-13 14:52:31
package com.yymt.common.utils; /** * @Author:xielin * @Description: * @Date:2020/6/3 14:14 * @Version: 1.0 */ import org.apache.http.HeaderElement; import org.apache.http.HeaderElementIterator; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeaderElementIterator; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; /** * @author xielin * http长连接 */ public class HttpClientLoop { private static Logger logger = LoggerFactory.getLogger(HttpClientLoop.class); /** * 构造请求实体 * * @param scehme * @param host * @param path * @return * @throws Exception */ public static URI constructURI(final String scehme, final String host, final String path) { URI uri = null; try { uri = new URIBuilder().setScheme(scehme) .setHost(host) .setPath(path).build(); } catch (URISyntaxException e) { e.printStackTrace(); } // List<NameValuePair> nvps // .setParameters(nvps).build(); return uri; } /** * http长轮询 长连接 * * @throws Exception */ public static void httpLongConnLoop(String host) { //http默认长连接策略 ConnectionKeepAliveStrategy directStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { //解析response信息 HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement element = it.nextElement(); String key = element.getName(); String value = element.getValue(); // 如果头部包含timeout信息,则使用 if (value != null && key.equalsIgnoreCase("timeout")) { // 超时时间设置为服务器指定的值 return Long.parseLong(value) * 1000; } } // 获取主机 HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); if (host.equalsIgnoreCase(target.getHostName())) { return 5 * 1000; } else { return 300 * 1000; } } }; // 设置 VideoStructurizationConstant.CLOSEABLE_HTTP_CLIENT = HttpClients.custom().setKeepAliveStrategy(directStrategy).build(); // 默认只能传键值对格式 // UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(nameValuePairList, "UTF-8"); } /** * 发送post请求 * * @param map * @param post * @param client */ public static void sendFeature(Map map, HttpPost post, CloseableHttpClient client) { // 将json格式转成 键值对格式 StringEntity entity = new StringEntity(GsonUtil.GsonToString(map), "utf-8");//解决中文乱码问题 entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); post.setEntity(entity); try { CloseableHttpResponse response = client.execute(post); // if (().getStatusCode() == 200) { // ("解析结果集____:" + (())); // } logger.info("存储id和特征值,返回的解析结果集--->" + EntityUtils.toString(response.getEntity())); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }