您的位置:首页 > 理论基础 > 计算机网络

单例模式,实现httpclient的封装,让android开发中,进行网络操作的时候更方便一点。

2014-05-24 17:06 656 查看
package com.example.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
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.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
* 进行http请求的工具类
*
* @author Administrator
*
*/
public class HttpClientUtils {

private static HttpClient httpClient = null;
private static final String CHARSET = HTTP.UTF_8;
private HttpClientUtils() {

}

/**
* post方式进行网络操作
*
* @param url
*            要访问的地址
* @param params
*            所要传的参数
* @return 响应的结果 包含返回的状态码和页面内容
* @throws IOException
* @throws ClientProtocolException
*/
public static Map<String, Object> postReqMoreResult(String url,
Map<String, String> params) throws ClientProtocolException,
IOException {
getHttpClient();
HttpResponse response = postReq4Reponse(url, params);
Map<String, Object> map = new HashMap<String, Object>();
map.put("StatusCode", response.getStatusLine().getStatusCode());
map.put("Content", EntityUtils.toString(response.getEntity()));
return map;
}

/**
* post请求
*
* @param url
*            所要请求的地址
* @param params
*            所要传的参数
* @return response
* @throws IOException
* @throws ClientProtocolException
*/
public static HttpResponse postReq4Reponse(String url,
Map<String, String> params) throws ClientProtocolException,
IOException {
getHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
if(params != null && !params.isEmpty()){
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator
.next();
BasicNameValuePair bnp = new BasicNameValuePair(entry.getKey(),
entry.getValue());
parameters.add(bnp);
}
}
HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
//response.getEntity().consumeContent();
return response;
}

/**
* 进行post请求,只获得页面内容
*
* @param url
*            要请求的地址
* @param params
*            所要传的参数
* @return 页面内容
* @throws ClientProtocolException
* @throws IOException
*/
public static String postReq4Content(String url, Map<String, String> params)
throws ClientProtocolException, IOException {
getHttpClient();
HttpResponse response = postReq4Reponse(url, params);
return EntityUtils.toString(response.getEntity());
}

/**
* 进行get请求,并且得到response
*
* @param url
*            所要请求的地址
* @return response
* @throws ClientProtocolException
* @throws IOException
*/
public static HttpResponse getReq4Response(String url)
throws ClientProtocolException, IOException {
getHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
return response;
}

/**
* 进行get请求,只得到页面内容
*
* @param url
*            所要请求的地址
* @return
* @throws IOException
* @throws ParseException
*/
public static String getReq4Content(String url) throws ParseException,
IOException {
getHttpClient();
HttpResponse response = getReq4Response(url);
return EntityUtils.toString(response.getEntity());
}

/**
* 进行get请求并且得到多个返回内容 例如响应码和响应内容
*
* @param url
*            所有请求的内容
* @return 存放结果的键值对
* @throws IOException
* @throws ClientProtocolException
*/
public static Map<String, Object> getReqMoreResult(String url)
throws ClientProtocolException, IOException {
getHttpClient();
HttpResponse response = getReq4Response(url);
Map<String, Object> map = new HashMap<String, Object>();
map.put("StatusCode", response.getStatusLine().getStatusCode());
map.put("Content", EntityUtils.toString(response.getEntity()));
return map;
}

/**
* post请求获得输入流
* @param url 所要请求的网络地址
* @param params 所要传递的参数
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static InputStream postReq4InputStream(String url, Map<String, String> params)
throws ClientProtocolException, IOException{
getHttpClient();
HttpResponse response = postReq4Reponse(url, params);
return response.getEntity().getContent();
}

/**
* get请求得到输入流
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static InputStream getReq4InputStream(String url)
throws ClientProtocolException, IOException{
getHttpClient();
HttpResponse response = getReq4Response(url);
return response.getEntity().getContent();
}

/**
* 单例模式实现httpClient
*/
public static synchronized HttpClient getHttpClient() {
if (httpClient == null) {
HttpParams params = new BasicHttpParams();
// 设置一些基本参数
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超时设置
/* 从连接池中取连接的超时时间 */
ConnManagerParams.setTimeout(params, 1000);
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(params, 2000);
/* 请求超时 */
HttpConnectionParams.setSoTimeout(params, 4000);
/* 是否可以重定向 */
HttpClientParams.setRedirecting(params, true);
// 设置我们的HttpClient支持HTTP和HTTPS两种模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));

// 使用线程安全的连接管理来创建HttpClient
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
params, schReg);
httpClient = new DefaultHttpClient(conMgr, params);
}
return httpClient;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐