java用httpclient 执行到httpclient.execute(request); 这句代码假死不往下执行不报错
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java用httpclient 执行到httpclient.execute(request); 这句代码假死不往下执行不报错相关的知识,希望对你有一定的参考价值。
之前看到你提到问题,我也遇到这个问题了,请问你是怎么解决的,方便告诉我吗?谢谢
参考技术A 这不一定是httpclient的问题。也很有可能是因为服务器没有响应造成的。可以通过调整超时时间解决。 参考技术B 1.关闭流httpClient.execute(httpGet).getEntity().getContent().close()
2.设置连接超时
SocketConfig socketConfig = SocketConfig.custom()
//开启监视TCP连接是否有效
.setSoKeepAlive(false)
//是否可以在一个进程关闭Socket后,即使它还没有释放端口,其它进程还可以立即重用端口
.setSoReuseAddress(true)
//接受数据的等待超时时间,单位ms
.setSoTimeout(70000)
//是否立即发送数据,设置为true会关闭Socket缓冲,默认为false
.setTcpNoDelay(true).build();
HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultSocketConfig(socketConfig);
httpClient = httpClientBuilder.build();
httpClient 配置与测试
1:pom.xml 输入依赖jar坐标
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> </dependencies>
2:测试配置成功源码
package com.ibaiqi.gather.httpClientStudy; import org.apache.http.HttpEntity; 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; import sun.net.www.http.HttpClient; import java.io.IOException; /** * @version 1.0.0 * @program: recuit_gather * @description: * @author: zhangdaxu * @create: 2020-03-13 10:47 */ public class httpClientStu01 { public static void main(String[] args) throws IOException { System.out.println("测试httpClient配置"); //1:创建httpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //2:通过httpGet发起get方式,传入网址为参数,并创建httpGet对象。 HttpGet httpGet = new HttpGet("http://www.itcast.cn"); //3:使用httpClient对象发起请求, CloseableHttpResponse response = httpClient.execute(httpGet); System.out.println(response); //4:解析响应,从页获取数据 //判断http状态码 if(response.getStatusLine().getStatusCode()==200){ //Entity是发送和接收信息载体、 httpEntity可能通过request或 reponse HttpEntity httpEntity = response.getEntity(); System.out.println("输出httpEntity对象"); System.out.println(httpEntity); //不加UTF-8参数,会中文乱码 String content = EntityUtils.toString(httpEntity,"UTF-8"); System.out.println("获取内容"+content); } } }
以上是关于java用httpclient 执行到httpclient.execute(request); 这句代码假死不往下执行不报错的主要内容,如果未能解决你的问题,请参考以下文章