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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值