本文目录
- closeablehttpclient httpclient 线程安全吗
- 如何接收httpclient发送的请求
- 如何使用httpclient访问网络
- HttpClient和HttpURLConnection的区别
- httpclient 需要关闭吗
- httpclient怎么抓取最终跳转的网站数据
- 如何使用HttpClient
- httpclient4怎么使用请求超时后的重试
- httpClient4整个应用应该使用同一个实例么
- 如何使用HttpClient模拟浏览器GET POST
closeablehttpclient httpclient 线程安全吗
安全的1、httpclient总结:一、基本知识准备(1)构建URI工具类,URIBuilder(2)HttpResponse类,可以添加Header信息获取所有Header信息的方法,调用HeaderIterator接口HeaderIterator it = response.headerIterator(“Set-Cookie“);while (it.hasNext()) {System.out.println(it.next());}(3)HttpEntity内容实体 可以被装入Request和Response中..只有独立的entity才可以被重复调用.当请求需要entity HttpEntity.writeTo(OutputStream)从响应中解析entity HttpEntity.getContent()HttpEntity.getContentType()HttpEntity.getContentLength()HttpEntity.getContentEncoding()对entity进行解析可采用流的方式或者调用EntityUtils,但后者有长度的限制2048利用 BufferedEntity可以将entity缓存到本地磁盘,用来进行多次读取.创建entity信息时需要指定meta信息,包括contentType(4)可以调用ResponseHandler写入响应统一处理二、常用策略keep-Alieve策略:自定义ConnectionKeepAliveStrategy重定向策略:LaxRedirectStrategy三、资源分配当CloseableHttpClient不再需要,并且不再连接管理的范围,需要调用CloseableHttpClient.close()方法将其关闭..四、HttpClient状态管理1、在HTTP上下文中,很多有逻辑关系的请求都可以放入到同一个session中..HttpClient本身线程HttpContext 包含任意的键值对,因此线程不安全..通常建议每个线程拥有自己的上下文 2、自动恢复机制----》HttpRequestRetryHandlerHttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {public boolean retryRequest(IOException exception,int executionCount,HttpContext context) {if (executionCount 》= 5) {// Do not retry if over max retry countreturn false;}if (exception instanceof InterruptedIOException) {// Timeoutreturn false;}if (exception instanceof UnknownHostException) {// Unknown hostreturn false;}if (exception instanceof ConnectTimeoutException) {// Connection refusedreturn false;}if (exception instanceof SSLException) {// SSL handshake exceptionreturn false;}HttpClientContext clientContext = HttpClientContext.adapt(context);HttpRequest request = clientContext.getRequest();boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);if (idempotent) {// Retry if the request is considered idempotentreturn true;}return false;}};CloseableHttpClient httpclient = HttpClients.custom().setRetryHandler(myRetryHandler).build();4、多线程中的应用AtomicInteger,,,,待研究...从连接管理器中获取连接(1)通过HttpClientConnectionManager来管理一个连接HttpClientContext context = HttpClientContext.create();HttpClientConnectionManager connMrg = new BasicHttpClientConnectionManager();HttpRoute route = new HttpRoute(new HttpHost(“www.yeetrack.com“, 80));// 获取新的连接. 这里可能耗费很多时间ConnectionRequest connRequest = connMrg.requestConnection(route, null);// 10秒超时HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);try {// 如果创建连接失败if (!conn.isOpen()) {// establish connection based on its route infoconnMrg.connect(conn, route, 1000, context);// and mark it as route completeconnMrg.routeComplete(conn, route, context);}// 进行自己的操作.} finally {connMrg.releaseConnection(conn, null, 1, TimeUnit.MINUTES);}通过更复杂的PoolingHttpClientConnectionManager来管理多个连接,适合多线程中的请求PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();// 将最大连接数增加到200cm.setMaxTotal(200);// 将每个路由基础的连接增加到20cm.setDefaultMaxPerRoute(20);//将目标主机的最大连接数增加到50HttpHost localhost = new HttpHost(“www.yeetrack.com“, 80);cm.setMaxPerRoute(new HttpRoute(localhost), 50);CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();示例1---------------------------------PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();// URL列表数组String urisToGet = {“http://www.domain1.com/“,“http://www.domain2.com/“,“http://www.domain3.com/“,“http://www.domain4.com/“};// 为每个url创建一个线程,GetThread是自定义的类GetThread threads = new GetThread[urisToGet.length];for (int i = 0; i 《 threads.length; i++) {HttpGet httpget = new HttpGet(urisToGet[i]);threads[i] = new GetThread(httpClient, httpget);}// 启动线程for (int j = 0; j 《 threads.length; j++) {threads[j].start();}// join the threadsfor (int j = 0; j 《 threads.length; j++) {threads[j].join();}自定义类GetThreadstatic class GetThread extends Thread {private final CloseableHttpClient httpClient;private final HttpContext context;private final HttpGet httpget;public GetThread(CloseableHttpClient httpClient, HttpGet httpget) {this.httpClient = httpClient;this.context = HttpClientContext.create();this.httpget = httpget;}@Overridepublic void run() {try {CloseableHttpResponse response = httpClient.execute(httpget, context);try {HttpEntity entity = response.getEntity();} finally {response.close();}} catch (ClientProtocolException ex) {// Handle protocol errors} catch (IOException ex) {// Handle I/O errors}}}注意:即使httpclient可以被多线程访问,仍建议每个httpclient采用自己的context5、 public static class IdleConnectionMonitorThread extends Thread {private final HttpClientConnectionManager connMgr;private volatile boolean shutdown;public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {super();this.connMgr = connMgr;}@Overridepublic void run() {try {while (!shutdown) {synchronized (this) {wait(5000);// 关闭失效的连接connMgr.closeExpiredConnections();// 可选的, 关闭30秒内不活动的连接connMgr.closeIdleConnections(30, TimeUnit.SECONDS);}}} catch (InterruptedException ex) {// terminate}}public void shutdown() {shutdown = true;synchronized (this) {notifyAll();}}}
如何接收httpclient发送的请求
客户端向服务器发送数据份两种情况SSL单向验证SSL双向验证1.SSL单向验证代码:Java代码 import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ClientSendData { static Log log = LogFactory.getLog(ClientSendData.class); private String Url; // 初始化数据 public ClientSendData() { Url = ““; } public String sendData(String data) { String receivedData = null; try { Map paramsData = new HashMap(); paramsData.put(“data“, data); receivedData = send(Url, paramsData); } catch (Exception e) { e.printStackTrace(); } return receivedData; } public static String send(String url, Map paramsMap) { String result = null; PostMethod postMethod = null; HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, “utf-8“); postMethod = new PostMethod(url); if (paramsMap != null && paramsMap.size() 》 0) { NameValuePair datas = new NameValuePair[paramsMap.size()]; int index = 0; for (String key : paramsMap.keySet()) { datas[index++] = new NameValuePair(key, paramsMap.get(key)); } postMethod.setRequestBody(datas); } HttpClientParams httparams = new HttpClientParams(); httparams.setSoTimeout(60000); postMethod.setParams(httparams); try { int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK) { result = postMethod.getResponseBodyAsString(); log.info(“发送功“); } else { log.error(“ http response status is “ + statusCode); } } catch (HttpException e) { log.error(“error url=“ + url, e); } catch (IOException e) { log.error(“error url=“ + url, e); } finally { if (postMethod != null) { postMethod.releaseConnection(); } } return result; } public static void main(String args) { ClientSendData t = new ClientSendData(); t.sendData(“测试SSL单项连接向服务端发送数据!“); } } 能现异1.java.net.ConnectException: Connection refused: connect服务器没启2 .javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed服务端证书信解决办见篇文章 3.java.net.SocketException: Software caused connection abort: recv failed由于服务端配置SSL双向认证客户端发送数据按照服务器单向认证发送即没客户端证书信息起发送给服务端4.org.apache.commons.httpclient.NoHttpResponseException般服务端防火墙原拦截客户端请求另外服务端负载重现问题5.javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake由于服务端配置SSL双向认证客户端发送数据按照服务器单向认证发送即没客户端证书信息起发送给服务端服务端验证客户端证书发现客户端没证书断握手连接2.SSL双向验证双向验证暂知道何用HTTPCLIENT发送数据需要双向验证发送数据参考我另外文章另外知道HTTPCLIENT何双向验证发送数据恳请指教
如何使用httpclient访问网络
使用Apache HttpClient访问网络
package com.szy.news.service;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import org.json.JSONObject;import com.szy.news.model.Parameter;/** *以同步方式发送Http请求 */public class SyncHttp{/** * 通过GET方式发送请求 * @param url URL地址 * @param params 参数 * @return * @throws Exception */public String httpGet(String url, String params) throws Exception{ String response = null; //返回信息//拼接请求URLif (null!=params&&!params.equals(““)){url += “?“ + params;} int timeoutConnection = 3000; int timeoutSocket = 5000; HttpParams httpParameters = new BasicHttpParams();// Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例// HttpClient httpClient = new DefaultHttpClient();HttpClient httpClient = new DefaultHttpClient(httpParameters); // 创建GET方法的实例HttpGet httpGet = new HttpGet(url);try{ HttpResponse httpResponse = httpClient.execute(httpGet);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) //SC_OK = 200{// 获得返回结果response = EntityUtils.toString(httpResponse.getEntity());JSONObject jsonObject = new JSONObject(response);}else{response = “返回码:“+statusCode;}} catch (Exception e){throw new Exception(e);} return response;}/** * 通过POST方式发送请求 * @param url URL地址 * @param params 参数 * @return * @throws Exception */public String httpPost(String url, List《Parameter》 params) throws Exception{String response = null;int timeoutConnection = 3000; int timeoutSocket = 5000; // Set the timeout in milliseconds until a connection is established.HttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT).in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 构造HttpClient的实例//HttpClient httpClient = new DefaultHttpClient();HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url);if (params.size()》=0){//设置httpPost请求参数httpPost.setEntity(new UrlEncodedFormEntity(buildNameValuePair(params),HTTP.UTF_8));}//使用execute方法发送HTTP Post请求,并返回HttpResponse对象HttpResponse httpResponse = httpClient.execute(httpPost);int statusCode = httpResponse.getStatusLine().getStatusCode();if(statusCode==HttpStatus.SC_OK){//获得返回结果response = EntityUtils.toString(httpResponse.getEntity());}else{response = “返回码:“+statusCode;}return response;}/** * 把Parameter类型集合转换成NameValuePair类型集合 * @param params 参数集合 * @return */private List《BasicNameValuePair》 buildNameValuePair(List《Parameter》 params){List《BasicNameValuePair》 result = new ArrayList《BasicNameValuePair》();for (Parameter param : params){BasicNameValuePair pair = new BasicNameValuePair(param.getName(), param.getValue());result.add(pair);}return result;}}
HttpClient和HttpURLConnection的区别
首先:在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。 在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。 其次:HttpClient是个很不错的开源框架,封装了访问
httpclient 需要关闭吗
需要用httpclient会为你管理cookie等东西,从而使得你保持登陆状态,你自己要注意的就是,登陆后要使用同一个httpclient对象
httpclient怎么抓取最终跳转的网站数据
1.服务器认证(Server Authentication)HttpClient处理服务器认证几乎是透明的,仅需要开发人员提供登录信息(login credentials)。登录信息保存在HttpState类的实例中,可以通过 setCredentials(String realm, Credentials cred)和getCredentials(String realm)来获取或设置。HttpClient内建的自动认证,可以通过HttpMethod类的setDoAuthentication(boolean doAuthentication)方法关闭,而且这次关闭只影响HttpMethod当前的实例。2.代理认证(proxy authentication) 除了登录信息需单独存放以外,代理认证与服务器认证几乎一致。用 setProxyCredentials(String realm, Credentials cred)和 getProxyCredentials(String realm)设、取登录信息。3.认证方案(authentication schemes)是HTTP中规定最早的也是最兼容的方案,遗憾的是也是最不安全的一个方案,因为它以明码传送用户名和密码。它要求一个UsernamePasswordCredentials实例,可以指定服务器端的访问空间或采用默认的登录信息。
如何使用HttpClient
HttpClient简单使用准备 Apache官网下载 HttpClient , 下不了的点击这里,下载完后解压取lib文件夹中jar包导入到项目中在进行本例之前需要了解三个类 HttpClient 代表Http客户端 里面定义了很多), 然后用客户端对某一个服务器执行请求操作,可以得到一个http响应, 这里响应 结构如下 消息状态行,消息头,消息实体 Response = Status-Line *(( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ]结构中的数据我已在本例运行结果中显示出来,请见上图,可以看出本例:对应结构消息状态行: HTTP/1.1 200 OK消息响应头:Date:Tue, 08 Jan 2013 07:18:42 GMTServer:BWS/1.0Content-Length:9785Content-Type:text/html;charset=gbkCache-Control:privateExpires:Tue, 08 Jan 2013 07:18:42 GMTSet-Cookie:H_PS_PSSID=1757; path=/; domain=.baidu.comSet-Cookie:BAIDUID=22B4BB1F8F8E808DB50B6513DBBCF6DF:FG=1; expires=Tue, 08-Jan-43 07:18:42 GMT; path=/; domain=.baidu.comP3P:CP=“ OTI DSP COR IVA OUR IND COM “Connection:Keep-Alive
httpclient4怎么使用请求超时后的重试
这样应该可以吧,httpclient4自带的HttpClientBuilder.create() .setDefaultRequestConfig(config) .setRetryHandler(new DefaultHttpRequestRetryHandler()) //默认失败后重发3次,可用别的构造方法指定重发次数 .build(); 自己写的int i = 0; while (true) { CloseableHttpResponse response =null; try{ response = httpClient.execute(httpPost); }catch(Exception e){ if(i》3){ break; } i++; } if (esponse!= null ) { break; } }
httpClient4整个应用应该使用同一个实例么
1、是整个应用使用同一个httpClient实例(写个单例工厂返回应用中唯一实例),还是应该每次做POST请求的时候new一个DefaultHttpClient对象? 2、做多线程并发POST时,该使用ThreadSafeClientConnManager还是普通默认的SingleClientConnManager? 3、在每次POST完成后,是否需要执行httpClient.getConnectionManager().shutdown()?
如何使用HttpClient模拟浏览器GET POST
JAVA-用HttpClient来模拟浏览器GET,POST一般的情况下我们都是使用IE或者Navigator浏览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据等等。所访问的这些页面 有的仅仅是一些普通的页面,有的需要用户登录后方可使用,或者需要认证以及是一些通过加密方式传输,例如HTTPS。目前我们使用的浏览器处理这些情况都 不会构成问题。不过你可能在某些时候需要通过程序来访问这样的一些页面,比如从别人的网页中“偷”一些数据;利用某些站点提供的页面来完成某种功能,例如 说我们想知道某个手机号码的归属地而我们自己又没有这样的数据,因此只好借助其他公司已有的网站来完成这个功能,这个时候我们需要向网页提交手机号码并从 返回的页面中解析出我们想要的数据来。如果对方仅仅是一个很简单的页面,那我们的程序会很简单,本文也就没有必要大张旗鼓的在这里浪费口舌。但是考虑到一 些服务授权的问题,很多公司提供的页面往往并不是可以通过一个简单的URL就可以访问的,而必须经过注册然后登录后方可使用提供服务的页面,这个时候就涉 及到COOKIE问题的处理。我们知道目前流行的动态网页技术例如ASP、JSP无不是通过COOKIE来处理会话信息的。为了使我们的程序能使用别人所 提供的服务页面,就要求程序首先登录后再访问服务页面,这过程就需要自行处理cookie,想想当你用 java.net.HttpURLConnection来完成这些功能时是多么恐怖的事情啊!况且这仅仅是我们所说的顽固的WEB服务器中的一个很常见的 “顽固”!再有如通过HTTP来上传文件呢?不需要头疼,这些问题有了“它”就很容易解决了!我们不可能列举所有可能的顽固,我们会 针对几种最常见的问题进行处理。当然了,正如前面说到的,如果我们自己使用java.net.HttpURLConnection来搞定这些问题是很恐怖 的事情,因此在开始之前我们先要介绍一下一个开放源码的项目,这个项目就是Apache开源组织中的本小节的例子演示向如何查询手机号码所在的城市,代码如下:/**//** Created on 2003-12-7 by Liudong*/package http.demo;import java.io.IOException;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.*;/** *//*** 提交参数演示* 该程序连接到一个用于查询手机号码所属地的页面* 以便查询号码段1330227所在的省份以及城市* @author Liudong*/public class SimpleHttpClient ...{public static void main(String args) throws IOException...{HttpClient client = new HttpClient();client.getHostConfiguration().setHost(“www.imobile.com.cn“, 80, “http“);HttpMethod method = getPostMethod();//使用POST方式提交数据client.executeMethod(method);//打印服务器返回的状态System.out.println(method.getStatusLine());//打印结果页面String response = new String(method.getResponseBodyAsString().getBytes(“8859_1“));//打印返回的信息System.out.println(response);method.releaseConnection();}/** *//*** 使用GET方式提交数据* @return*/private static HttpMethod getGetMethod()...{return new GetMethod(“/simcard.php?simcard=1330227“);}/** *//*** 使用POST方式提交数据* @return*/private static HttpMethod getPostMethod()...{PostMethod post = new PostMethod(“/simcard.php“);NameValuePair simcard = new NameValuePair(“simcard“,“1330227“);post.setRequestBody(new NameValuePair ...{ simcard});return post;}}