`
月下独酌
  • 浏览: 130259 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

httpclient

阅读更多
//自定义httpclient

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
 
public class CustHttpClient extends DefaultHttpClient { 
	
	public static final int SET_CONNECTION_TIMEOUT = 15 * 1000;
	public static final int SET_SOCKET_TIMEOUT = 15 * 1000;
	
    public CustHttpClient() { 
        super(); 
        registerTrustAllScheme();
        setCredentials(); 
        HttpConnectionParams.setConnectionTimeout(this.getParams(), SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(this.getParams(), SET_SOCKET_TIMEOUT);
        HttpProtocolParams.setContentCharset(this.getParams(), HTTP.UTF_8);
    } 
    
    private void registerTrustAllScheme() {
    	Scheme httpSch = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    	getConnectionManager().getSchemeRegistry().register(httpSch); 
    	TrustAllSSLSocketFactory tasslf = null;
		try {
			tasslf = new TrustAllSSLSocketFactory();
		} catch (KeyManagementException e) {
		} catch (NoSuchAlgorithmException e) {
		} catch (KeyStoreException e) {
		} catch (UnrecoverableKeyException e) {
		} 
		if (tasslf != null) {
			Scheme httpSSch = new Scheme("https", tasslf, 443); 
			getConnectionManager().getSchemeRegistry().register(httpSSch);			
		}
    }
      
    private void setCredentials() {
        BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
        // username password not needed
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", "");
        cP.setCredentials(AuthScope.ANY, creds); 
        setCredentialsProvider(cP); 
    } 
    
    public static class TrustAllSSLSocketFactory extends SSLSocketFactory { 
        private javax.net.ssl.SSLSocketFactory factory; 

        public TrustAllSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { 
            super(null); 
            try { 
                SSLContext sslcontext = SSLContext.getInstance("TLS"); 
                sslcontext.init(null, new TrustManager[] { new TrustAllManager() }, null);
                factory = sslcontext.getSocketFactory();
                setHostnameVerifier(new AllowAllHostnameVerifier());             
            } catch(Exception ex) { } 
        } 
        
        public static SocketFactory getDefault() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { return new TrustAllSSLSocketFactory(); } 
        public Socket createSocket() throws IOException { return factory.createSocket(); } 
        public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException { return factory.createSocket(socket, s, i, flag); } 
        public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException { return factory.createSocket(inaddr, i, inaddr1, j); } 
        public Socket createSocket(InetAddress inaddr, int i) throws IOException { return factory.createSocket(inaddr, i); } 
        public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException { return factory.createSocket(s, i, inaddr, j); } 
        public Socket createSocket(String s, int i) throws IOException { return factory.createSocket(s, i); } 
        public String[] getDefaultCipherSuites() { return factory.getDefaultCipherSuites(); } 
        public String[] getSupportedCipherSuites() { return factory.getSupportedCipherSuites(); } 
    }
    
    public static class TrustAllManager implements X509TrustManager { 
        public void checkClientTrusted(X509Certificate[] cert, String authType) throws CertificateException { } 
        public void checkServerTrusted(X509Certificate[] cert, String authType) throws CertificateException { } 
        public X509Certificate[] getAcceptedIssuers() { return null; } 
    } 
}


用法。。。

	private HttpPost getHttpPost(String url) {
		HttpPost postMethod = new HttpPost(url);
		postMethod.setHeader("Content-Type",
				"application/x-www-form-urlencoded; charset=UTF-8");
		return postMethod;
	}

	private HttpPost getHttpPost(String url, String pKey, String pValue) {
		HttpPost postMethod = getHttpPost(url);
		HttpParams httpParams = postMethod.getParams();
		try {
			postMethod.setEntity(new UrlEncodedFormEntity(setMethodParamList(
					pKey, pValue), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
		}
        HttpConnectionParams.setConnectionTimeout(httpParams, TheStoreHttpClient.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, TheStoreHttpClient.SET_SOCKET_TIMEOUT);
		
		return postMethod;
	}

public HttpResponse getHttpResponse(String pKey, String pValve) {
		
		HttpPost postMethod = getHttpPost(pKey, pValve);
        HttpClient client  = new CustHttpClient();
        //client.getParams().setParameter(
						ConnRouteParams.DEFAULT_PROXY, new HttpHost("http://xx.xx.xx.xx", 80))
        HttpResponse httpResponse = null;
		try {
			httpResponse = client.execute(postMethod);
			if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				//当http状态不是200时终止执行??
				postMethod.abort();
			}
		} catch (ClientProtocolException e) {
			postMethod.abort();
			client.getConnectionManager().shutdown();
		} catch (java.net.SocketTimeoutException e) {
			postMethod.abort();
			client.getConnectionManager().shutdown();
		} catch (IOException e) {
			postMethod.abort();
			client.getConnectionManager().shutdown();
		} 
		return httpResponse;
	}


httpclient 存在转发时获取新的地址
    public static String getJoinUri(String uri) {
        String joinUri = null;
    	if (uri == null || "".equals(uri)){
    		Log.w(UpgradeApplication.TAG,"getJoinuri is null or empty");
    		return joinUri;
    	}
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        setProxy(request, httpClient);
        HttpResponse response = null;
        request.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
        		UpgradeApplication.config.getSo_timeout());
        request.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
        		UpgradeApplication.config.getConnection_timeout());
        request.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        try {
            response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (!isRedirectRequested(statusCode)) {
                return null;
            }
            String locationHeader = response.getFirstHeader("Location").getValue();
            URI mUri = URI.create(locationHeader);
            if (!mUri.isAbsolute()) {
                try {
                    URI requestURI = new URI(request.getRequestLine().getUri());
                    mUri = URIUtils.resolve(requestURI, locationHeader);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
            joinUri = mUri.toString();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
			if (httpClient != null
					&& httpClient.getConnectionManager() != null) {
				httpClient.getConnectionManager().shutdown();
				httpClient = null;
			}
		}
        return joinUri;
    }


AndroidHttpClient 下载时获取文件大小
 public static long getSize(String zipurl,Context context) {
    	if (zipurl == null || "".equals(zipurl)){
    		Log.w(UpgradeApplication.TAG,"getJoinuri is null or empty");
    		return 0l;
    	}
    	AndroidHttpClient client = AndroidHttpClient.newInstance("AndroidDownloadManager", context);
		HttpResponse response = null;
		Header header = null;
		HttpGet request = new HttpGet(zipurl);
		HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters,
        			5 * 1000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5 * 1000);
		request.setParams(httpParameters);
		try{
			response = client.execute(request);
			header = response.getFirstHeader("Content-Length");
		} catch (IllegalArgumentException ex) {
			Log.e(UpgradeApplication.TAG, "IllegalArgumentException", ex);
			header = null;
			request.abort();
    	} catch (java.net.SocketException se) {
    		Log.e(UpgradeApplication.TAG, "IOException", se);
			header = null;
			request.abort();
		}  catch (java.io.IOException ioe) {
    		Log.e(UpgradeApplication.TAG, "IOException", ioe);
			header = null;
			request.abort();
		} finally {
			if (client != null) {
                client.close();
                client = null;
            }
		} 
		String headerContentLength = null;
		if (header != null) {
                headerContentLength = header.getValue();
        }
		long length = headerContentLength != null ? Long.parseLong(headerContentLength):-1L;
		return length;
    }
分享到:
评论
1 楼 shenzhenyuyuyu 2011-06-01  
用httpclinet4.0模拟登录新浪微博,抓包后分析上传参数,密码加密了,我将加密的密文和各种参数上传登录不了(获得不了cookie),后来我用了其他的方法,就是登录新浪会员(密码是明文),然后跳转到微博,成功过,但现在不行了,跳转cookie被拒绝,求大神指教啊,我纠结了很久

相关推荐

    httpclient.jar包下载

    《深入解析httpclient.jar及其与code.jar的关联》 在Java开发中,HTTP通信是不可或缺的一部分,而Apache HttpClient库正是Java实现HTTP客户端操作的重要工具。本文将深入探讨httpclient.jar包,以及它与code.jar包...

    HttpClient4.2.1版本的Jar包

    HttpClient 4.2.1版本引入了一些重要的改进和修复,以提高性能和稳定性。以下是一些关键特性: 1. **连接管理**:HttpClient 4.2.1引入了更完善的连接管理机制,允许开发者控制连接的创建、复用和关闭。`...

    HttpClient 3.x to HttpComponents HttpClient 4.x

    例如,在HttpClient 3.x中,代码可能会使用`***mons.httpclient.HttpClient`类和`***mons.httpclient.methods.GetMethod`等,而在4.x版本中,这些都被新的API所替代。程序员需要熟悉`org.apache....

    httpclient-4.2.5-API文档-中文版.zip

    赠送jar包:httpclient-4.2.5.jar; 赠送原API文档:httpclient-4.2.5-javadoc.jar; 赠送源代码:httpclient-4.2.5-sources.jar; 赠送Maven依赖信息文件:httpclient-4.2.5.pom; 包含翻译后的API文档:httpclient...

    httpclient4.2.1.zip

    本文将深入探讨HttpClient 4.2.1的核心特性和使用方法,帮助开发者更好地理解和应用这个强大的工具。 一、HttpClient简介 HttpClient是一个开放源码的Java库,由Apache软件基金会维护。它为Java程序员提供了一个...

    httpClient

    HttpClient httpClient = new HttpClient(); // 设置 Http 连接超时为5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2 生成 GetMethod 对象并设置参数 */ GetMethod ...

    httpclient方式调用url

    本篇文章将深入探讨如何使用HttpClient方式调用URL,以及相关的知识点。 首先,HttpClient允许我们构建复杂的HTTP请求,包括GET、POST以及其他HTTP方法。使用HttpClient调用URL的基本步骤包括创建HttpClient实例、...

    httpclient-4.5.6-API文档-中文版.zip

    赠送jar包:httpclient-4.5.6.jar; 赠送原API文档:httpclient-4.5.6-javadoc.jar; 赠送源代码:httpclient-4.5.6-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.6.pom; 包含翻译后的API文档:httpclient...

    HttpClientHelper 工具类

    HttpClientHelper 对这个类进行了封装,使得开发者无需直接与HttpClient接口打交道,而是通过更简洁、易用的方法调用来实现网络通信。这提高了代码的可读性和可维护性。 单例模式是软件设计模式的一种,确保一个类...

    HttpClient所需jar包(全) httpClient.4.13jar

    HttpClient 4.13版本是这个库的一个较新版本,包含了一系列的改进和修复。 在Java开发中,HttpClient是一个常用的工具,尤其在处理Web服务或者API调用时。它支持同步和异步操作,可以处理复杂的HTTP协议细节,使...

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    这个实例主要涉及如何配置HttpClient来忽略SSL(Secure Socket Layer)验证,这对于在开发和测试环境中处理自签名证书或未认证的服务器非常有用。以下将详细介绍HttpClient的使用以及如何进行SSL验证的忽略。 首先...

    httpClient需要的jar包

    本压缩包文件"httpClient"很可能包含了HttpClient库所需的必备JAR文件,这些文件通常包括HttpClient的核心库、依赖的第三方库以及可能的扩展模块。为了正确使用HttpClient,你需要确保将这些JAR文件添加到你的项目类...

    HttpClient 调用WebService示例

    在本文中,我们将深入探讨如何使用HttpClient调用WebService。 首先,调用WebService通常涉及SOAP(Simple Object Access Protocol)或RESTful API。HttpClient可以处理这两种类型的Web服务。在本示例中,我们假设...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    httpclient-4.5.13-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    Java HttpClient 全部的jar包

    在Java项目中,使用HttpClient可以实现与Web服务器的高效通信。下面将详细介绍这12个jar包的作用及其在HttpClient中的功能: 1. `commons-beanutils-1.8.0.jar`: Apache Commons BeanUtils库提供了对Java Beans属性...

    HTTPClient

    ### HTTPClient知识点详解 #### 1. HttpClient4 – 获取状态码 **1.1 概览** 本节将详细介绍如何使用HttpClient 4.x版本来获取HTTP响应的状态码,并对其进行验证。这对于开发人员来说是一个非常实用的功能,可以...

    httpClient组合包.zip

    此外,HttpClient还支持异步操作,可以在多线程环境中高效地处理并发请求。 2. **httpcore-4.4.12.jar**:这是HttpClient的核心库,包含了HTTP协议的基本组件,如连接管理、请求和响应模型、编码器和解码器等。...

    Android HttpClient用到的jar包

    本篇将详细讲解如何利用Apache HttpClient及其相关的jar包在Android环境中进行文件上传。 首先,我们关注的是标题提到的两个jar包:“apache-mime4j-0.6.jar”和“httpmime-4.0.jar”。这两个jar包是HttpClient库的...

Global site tag (gtag.js) - Google Analytics