闲着没有事情,封装了一个HttpClient请求工具类,包含了超时时间,设置代理,支持HTTP与HTTPS, 已经GET和POST两种网络请求方式,复制代码到你的项目就能用!!
package com.mars.test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.text.TextUtils;
/**
* HTTP请求工具类
*
* @author Administrator
*
*/
public class HttpUtils {
private static final String TAG = "HttpUtils";
private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8 * 1024; // 8KB
private static final int MAX_CONNECTIONS = 10; // HTTP请求最大并发连接数
private static final int SOCKET_TIMEOUT = 55 * 1000; // 55s
private static final String MAP_KEY_APN = "apn";
private static final String MAP_KEY_APN_PROXY = "apn_proxy";
private static final String MAP_KEY_APN_PORT = "apn_port";
@SuppressWarnings("deprecation")
public static HashMap<String, Object> getNetInfo(Context context) {
HashMap<String, Object> hashMap = null;
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
if (null != activeNetworkInfo) {
if (ConnectivityManager.TYPE_MOBILE == activeNetworkInfo.getType()) {
String apn = activeNetworkInfo.getExtraInfo();
String apnProxy = Proxy.getDefaultHost();
int apnPort = Proxy.getDefaultPort();
hashMap = new HashMap<String, Object>();
hashMap.put(MAP_KEY_APN, apn);
hashMap.put(MAP_KEY_APN_PROXY, apnProxy);
hashMap.put(MAP_KEY_APN_PORT, apnPort);
}
}
return hashMap;
}
/**
* 创建并初始化HttpClient对象
*
* @return
*/
public static DefaultHttpClient create(Context context, String url) {
DefaultHttpClient httpClient = null;
BasicHttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, SOCKET_TIMEOUT);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
new ConnPerRouteBean(MAX_CONNECTIONS));
ConnManagerParams.setMaxTotalConnections(httpParams, 10);
HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);
HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_TIMEOUT);
HttpConnectionParams.setTcpNoDelay(httpParams, true);
HttpConnectionParams.setSocketBufferSize(httpParams,
DEFAULT_SOCKET_BUFFER_SIZE);
String agentProperty = System.getProperty("http.agent");
if (!TextUtils.isEmpty(agentProperty)) {
httpParams.setParameter(CoreProtocolPNames.USER_AGENT,
System.getProperty("http.agent"));
}
if (null != url && url.startsWith("https://")) {
// 支持HTTP与HTTPS
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// ThreadSafeClientConnManager线程安全管理类
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
httpParams, schemeRegistry);
httpClient = new DefaultHttpClient(cm, httpParams);
} else {
httpClient = new DefaultHttpClient(httpParams);
}
HashMap<String, Object> netInfo = getNetInfo(context);
if (null != netInfo) {
String apn = (String) netInfo.get(MAP_KEY_APN);
String apnProxy = (String) netInfo.get(MAP_KEY_APN_PROXY);
int apnPort = (Integer) netInfo.get(MAP_KEY_APN_PORT);
// 判断是否需要设置代理信息
if (null != apn && !"".equals(apnProxy) && null != apnProxy
&& -1 != apnPort) {
// 设置代理信息
HttpHost host = new HttpHost(apnProxy, apnPort);
httpClient.getParams().setParameter(
ConnRoutePNames.DEFAULT_PROXY, host);
}
}
return httpClient;
}
/**
* 将JSON 发送至后台服务器
*
* @param jsonString
* @return 服务器可能返回的响应数据
* @throws IOException
* @throws IllegalStateException
*/
public static String sendJson2Server(Context context, String jsonString,
List<BasicNameValuePair> params, String sendAddress)
throws IllegalStateException, IOException {
if (null != sendAddress) {
HttpPost post = new HttpPost(sendAddress);
// ByteArrayEntity entity = null;
ByteArrayOutputStream out = null;
InputStream in = null;
LogUtil.info(TAG, "sending data to " + sendAddress);
try {
// entity = new ByteArrayEntity(jsonString.getBytes("utf-8"));
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpClient client = create(context, sendAddress);
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
LogUtil.info(TAG, "response code: " + responseCode);
if (200 == responseCode) {
in = response.getEntity().getContent();
byte[] buf = new byte[1024];
int len;
out = new ByteArrayOutputStream();
while (-1 != (len = in.read(buf))) {
out.write(buf, 0, len);
}
byte[] byteArray = out.toByteArray();
return new String(byteArray, "utf-8");
}
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 从服务器获取数据
*
* @return
* @throws IOException
*/
public static String getDataFromServer(Context context, String url)
throws IOException {
HttpGet get = new HttpGet(url);
HttpResponse execute = null;
ByteArrayOutputStream out = null;
InputStream content = null;
try {
HttpClient httpClient = create(context, url);
execute = httpClient.execute(get);
if (200 == execute.getStatusLine().getStatusCode()) {
content = execute.getEntity().getContent();
out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while (-1 != (len = content.read(buf))) {
out.write(buf, 0, len);
}
return new String(out.toByteArray(), "utf-8");
}
} finally {
if (out != null) {
out.close();
}
if (content != null) {
content.close();
}
}
return null;
}
}
设置尝试重连
client.setHttpRequestRetryHandler(myRetryHandler);
/**
* 尝试重连
*/
public static HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
if (executionCount >= 3) {
// 如果超过最大重试次数,那么就不要继续了
return false;
}
if (exception instanceof NoHttpResponseException) {
// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {
// 不要重试SSL握手异常
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// 如果请求被认为是幂等的,那么就重试
return true;
}
return false;
}
};