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


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;
import sun.net.www.http.HttpClient;

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

    private static volatile 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 HttpClient getHttpClient() {
        if (httpClient == null) {
            synchronized (HttpClientUtils.class) {
                if (httpClient == null) {
                    httpClient = initHttpClient();
                }
            }
        }
        return httpClient;
    }

    private static HttpClient initHttpClient() {
        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);
        return new DefaultHttpClient(conMgr, params);
    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值