在这篇文章中,我们将带领您了解ApacheHttpClient超时的全貌,包括apache超时时间的相关情况。同时,我们还将为您介绍有关androidstudio没有org.apache.http.c
在这篇文章中,我们将带领您了解Apache HttpClient超时的全貌,包括apache超时时间的相关情况。同时,我们还将为您介绍有关android studio没有org.apache.http.client.HttpClient;等包问题 解决方案、Android无法访问org.apache.http.client.HttpClient、Apache HttpClient (理解Http Client)、apache HttpClient 4.5.2 模拟请求http的知识,以帮助您更好地理解这个主题。
本文目录一览:- Apache HttpClient超时(apache超时时间)
- android studio没有org.apache.http.client.HttpClient;等包问题 解决方案
- Android无法访问org.apache.http.client.HttpClient
- Apache HttpClient (理解Http Client)
- apache HttpClient 4.5.2 模拟请求http
Apache HttpClient超时(apache超时时间)
有没有办法为整个执行指定超时时间HttpClient
?
我尝试了以下方法:
httpClient.getParams().setParameter("http.socket.timeout", timeout * 1000);httpClient.getParams().setParameter("http.connection.timeout", timeout * 1000);httpClient.getParams().setParameter("http.connection-manager.timeout", new Long(timeout * 1000));httpClient.getParams().setParameter("http.protocol.head-body-timeout", timeout * 1000);
它实际上可以正常工作,除非远程主机发送回数据(即使以一字节/秒的速度),也将永远读取!但是无论主机是否响应,我都希望在10秒内中断连接。
答案1
小编典典当前无法设置这种 最大请求持续时间 :基本上,您想说 我不在乎任何特定的请求阶段是否超时,但是整个请求的持续时间不得超过15秒 (例如) 。
最好的选择是运行一个单独的计时器,当计时器到期时,获取HttpClient实例使用的连接管理器并关闭连接,这将终止链接。让我知道这是否适合您。
android studio没有org.apache.http.client.HttpClient;等包问题 解决方案
以前用Eclipse做
Android无法访问org.apache.http.client.HttpClient
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGetHC4; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class HTTPHelper { private String base; public HTTPHelper (String base) { this.base = base; } public String doGet (String path) { try { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGetHC4 get = new HttpGetHC4(path); CloseableHttpResponse response = client.execute(get); return ""; } catch (Exception e) { return null; } } }
问题是Android Studio标记了这一行
client.execute(get);
有错误:
说“无法访问org.apache.http.client.HttpClient”
这是我的gradle文件:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsversion "23.0.0" defaultConfig { applicationId "principal.halloween" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro' } } } dependencies { compile filetree(dir: 'libs',include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.0.0' compile 'com.pubnub:pubnub-android:3.7.5' compile 'com.google.code.gson:gson:2.3.1' compile group: 'org.apache.httpcomponents',name: 'httpclient-android',version: '4.3.5.1' compile 'org.apache.httpcomponents:httpclient:4.3.6' }
解决方法
不推荐使用HttpClient,因为它推断,您可以在HttpURLConnection中迁移代码
https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
您可以使用此功能,但不建议使用此功能
android { useLibrary 'org.apache.http.legacy' }
对于HttpURLConnection
URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect();
Apache HttpClient (理解Http Client)
The Apache HttpComponents™ project is responsible for creating and maintaining a toolset of low level Java components focused on HTTP and associated protocols. Include HttpClient, HttpCore, HttpAsyncClient three sub projects.
HttpClient
HTTP 协议(1.0 ,1.1)的实现,更多的是面向开发者使用的API,用于发起Http请求。请求的执行(excute()),拦截(interceptor),请求路由(route),请求代理(proxy),请求认证(发起Https验证,Oauth认证等), 请求结果的处理(ResponseHandler), 异常处理等基本操作封装和配置,同时允许使用者高度配置。
基本包含以下内容:
- 怎么发起http 和 https 请求
- 怎么通过代理发起请求
- 怎么接收返回值
- 怎么配置连接池,连接和执行线程的关系
- 怎么设置cookie,和一些认证信息
- 怎么配置长连接
- 设置超时,以及为什么要设置超时
Tips: HttpClient实例是可以线程共享的。
就以Apache HttpClient 提供的config example 来看一下。
/**
* This example demonstrates how to customize and configure the most common aspects
* of HTTP request execution and connection management.
*/
public class ClientConfiguration {
public final static void main(String[] args) throws Exception {
// Use custom message parser / writer to customize the way HTTP
// messages are parsed from and written out to the data stream.
HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
@Override
public HttpMessageParser<HttpResponse> create(
SessionInputBuffer buffer, MessageConstraints constraints) {
LineParser lineParser = new BasicLineParser() {
@Override
public Header parseHeader(final CharArrayBuffer buffer) {
try {
return super.parseHeader(buffer);
} catch (ParseException ex) {
return new BasicHeader(buffer.toString(), null);
}
}
};
return new DefaultHttpResponseParser(
buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) {
@Override
protected boolean reject(final CharArrayBuffer line, int count) {
// try to ignore all garbage preceding a status line infinitely
return false;
}
};
}
};
HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
// Use a custom connection factory to customize the process of
// initialization of outgoing HTTP connections. Beside standard connection
// configuration parameters HTTP connection factory can define message
// parser / writer routines to be employed by individual connections.
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
requestWriterFactory, responseParserFactory);
// Client HTTP connection objects when fully initialized can be bound to
// an arbitrary network socket. The process of network socket initialization,
// its connection to a remote address and binding to a local one is controlled
// by a connection socket factory.
// SSL context for secure connections can be created either based on
// system or application specific properties.
SSLContext sslcontext = SSLContexts.createSystemDefault();
// Create a registry of custom connection socket factories for supported
// protocol schemes.
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
// Use custom DNS resolver to override the system DNS resolution.
DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("myhost")) {
return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };
} else {
return super.resolve(host);
}
}
};
// Create a connection manager with custom configuration.
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry, connFactory, dnsResolver);
// Create socket configuration
SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.build();
// Configure the connection manager to use socket configuration either
// by default or for a specific host.
connManager.setDefaultSocketConfig(socketConfig);
connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);
// Validate connections after 1 sec of inactivity
connManager.setValidateAfterInactivity(1000);
// Create message constraints
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
// Configure the connection manager to use connection configuration either
// by default or for a specific host.
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
// Configure total max or per route limits for persistent connections
// that can be kept in the pool or leased by the connection manager.
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
// Use custom cookie store if necessary.
CookieStore cookieStore = new BasicCookieStore();
// Use custom credentials provider if necessary.
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// Create global request configuration
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setExpectContinueEnabled(true)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
.build();
// Create an HttpClient with the given custom dependencies and configuration.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultCookieStore(cookieStore)
.setDefaultCredentialsProvider(credentialsProvider)
.setProxy(new HttpHost("myproxy", 8080))
.setDefaultRequestConfig(defaultRequestConfig)
.build();
try {
HttpGet httpget = new HttpGet("http://httpbin.org/get");
// Request configuration can be overridden at the request level.
// They will take precedence over the one set at the client level.
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setProxy(new HttpHost("myotherproxy", 8080))
.build();
httpget.setConfig(requestConfig);
// Execution context can be customized locally.
HttpClientContext context = HttpClientContext.create();
// Contextual attributes set the local context level will take
// precedence over those set at the client level.
context.setCookieStore(cookieStore);
context.setCredentialsProvider(credentialsProvider);
System.out.println("executing request " + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget, context);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("----------------------------------------");
// Once the request has been executed the local context can
// be used to examine updated state and various objects affected
// by the request execution.
// Last executed request
context.getRequest();
// Execution route
context.getHttpRoute();
// Target auth state
context.getTargetAuthState();
// Proxy auth state
context.getTargetAuthState();
// Cookie origin
context.getCookieOrigin();
// Cookie spec used
context.getCookieSpec();
// User security token
context.getUserToken();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
HttpConnection, Socket and Thread
HttpConnection, Http连接是复杂的,有状态的,非线程安全的对象,它需要恰当的管理以便正确地执行功 能。 “HTTP 连接”一次仅只能由一个执行线程来使用。 HttpClient 采用一个特殊实体来 管理访问 HTTP 连接,这被称为 HTTP 连接管理器,ClientConnectionManager接口就是代表。HTTP 连接管理器的目的是作为工厂创建新的 HTTP 连接,管理持久连接的生命周期和同步访问持久连接(确保同一时间仅有一个线程可以访问一个连接)。内部的 HTTP 连接管理器使用 OperatedClientConnection 实例,这个实例为真正的连接扮演了一个代理,来管理连接状态和控制I/O操作的执行。如果一个管理的连接被释放或者被使用者明确地关闭,潜在的连接就会从它的代理分离,退回到管理器中。 尽管“服务消费者”仍然保存一个代理实例的引用。它也不能执行任何I/O操作、有意或无意地改变真实连接的状态。
first : HttpConnection 由ClientConnectionManager 管理,确保同一时间仅有一个线程可以访问一个连接,
Socket(java.net.Socket), This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines. The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.
second : 然后通过SocketFactory创建Socket来建立连接,Thread block until response return or timeout.
HttpClientContext clientContext = HttpClientContext.create();
PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
Socket socket = sf.createSocket(clientContext);
int timeout = 1000; //ms
HttpHost target = new HttpHost("localhost");
InetSocketAddress remoteAddress = new InetSocketAddress(
InetAddress.getByAddress(new byte[] {127,0,0,1}), 80);
sf.connectSocket(timeout, socket, target, remoteAddress, null, clientContext);
###Conclusion 关于HttpClient 的详细内容你应该读这篇文章 Http Client,这里介绍了Spring RestTemplate 中使用HttpClient,以及为什么很多人喜欢使用HttpClient (因为它的高度可配置化)。
###Reference
- HttpClient4.5中文翻译
- Apache HttpClient Example
apache HttpClient 4.5.2 模拟请求http
简介
借鉴地址
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
- 创建CloseableHttpClient对象。
- 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
- 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
- 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
- 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
- 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
- 释放连接。无论执行方法是否成功,都必须释放连接
实际使用场景:
pom依赖:
<!--apache模拟http请求--> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency>
测试类:
import com.jie.common.file.FileUtils; import com.jie.common.httprequest.HttpClientUtils; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2018/3/9 16:20 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ public class HttpRequestDemo { @Test public void httpRequestTest(){ String filePath = "D:\\tmp\\alibaba.html"; // 地址是我alibaba提供的StringUtils中的main方法里获取的测试地址...... String postUrl = "http://www.alibaba.com/trade/search"; Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put("fsb","y"); paramMap.put("IndexArea","product_en"); paramMap.put("CatId",""); paramMap.put("SearchText","test"); try { FileUtils.writeTxtToFile(HttpClientUtils.simplePost(postUrl,paramMap,""),filePath); } catch (IOException e) { e.printStackTrace(); } } }
工具类:
import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2018/3/9 15:55 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ public class HttpClientUtils { private static Log log = LogFactory.getLog(HttpClientUtils.class); private final static String DEFAULT_ENCODING = "UTF-8"; private final static int DEFAULT_CONNECT_TIMEOUT = 5000; // 设置连接超时时间,单位毫秒 private final static int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 1000;// 设置从connect Manager获取Connection 超时时间,单位毫秒 private final static int DEFAULT_SOCKET_TIMEOUT = 5000;// 请求获取数据的超时时间,单位毫秒 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用 /** * 简单http post请求 * @author wugong * @date 2018/3/9 16:18 * @modify if true,please enter your name or update time * @param */ public static String simplePost(String url, Map<String,String> paramMap, String encoding) throws ParseException, IOException { String body = ""; encoding = StringUtils.isBlank(encoding)?DEFAULT_ENCODING:encoding; //创建httpclient对象 CloseableHttpClient client = HttpClients.createDefault(); //创建post方式请求对象 HttpPost httpPost = postForm(paramMap,url,DEFAULT_ENCODING); //执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = null; try { response = client.execute(httpPost); //获取结果实体 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); }catch (UnsupportedEncodingException e){ e.printStackTrace(); log.error("简单post请求遇到UnSpEcode异常",e); throw new IOException(e); } catch (IOException e) { e.printStackTrace(); log.error("简单post请求遇到IO异常",e); throw new IOException(e); } catch (ParseException e) { e.printStackTrace(); log.error("简单post请求遇到PE异常",e); throw new ParseException(); } finally{ //释放链接 response.close(); } return body; } /** * post请求url与请求参数组装 * @author wugong * @date 2018/3/9 16:02 * @modify if true,please enter your name or update time * @param */ private static HttpPost postForm(Map<String,String> paramMap,String url,String encoding) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(url); //装填参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(paramMap!=null){ for (Map.Entry<String, String> entry : paramMap.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //设置参数到请求对象中 httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); //设置header信息 //指定报文头【Content-type】、【User-Agent】 httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build(); httpPost.setConfig(requestConfig); return httpPost; } }
import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * \* Created with IntelliJ IDEA. * \* User: wugong.jie * \* Date: 2018/3/9 16:36 * \* To change this template use File | Settings | File Templates. * \* Description: * \ */ public class FileUtils { private static final Log LOG = LogFactory.getLog(FileUtils.class); /** * 纯文本文件内容写入文件file * @author wugong * @date 2018/3/9 16:38 * @modify if true,please enter your name or update time * @param */ public static void writeTxtToFile(String txt,String filePath) throws IOException { try { File file = new File(filePath); if (!file.exists()) {//如果文件不存在 try { file.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } FileOutputStream fos = new FileOutputStream(file); // 通过文件输入流,写入文件内容 fos.write(txt.getBytes("utf-8")); fos.close(); } catch (IOException e) { e.printStackTrace(); LOG.error("纯文本文件写入file遇到IO异常", e); throw new IOException(e); } } }
今天关于Apache HttpClient超时和apache超时时间的分享就到这里,希望大家有所收获,若想了解更多关于android studio没有org.apache.http.client.HttpClient;等包问题 解决方案、Android无法访问org.apache.http.client.HttpClient、Apache HttpClient (理解Http Client)、apache HttpClient 4.5.2 模拟请求http等相关知识,可以在本站进行查询。
本文标签: