HttpUtil工具类

简介:

原文:http://zhelong111.iteye.com/blog/1407117

/**
 * 增强型Http辅助类
 * @author zhouli
 *
 */
public class EnhancedHttpUtil { 
	
	private static HttpClient httpClient; 
	private static final String TAG = "HttpUtil";
	
	/**
	 * 获得线程安全的HttpClient对象,能够适应多线程环境
	 * @return
	 */
	public static synchronized HttpClient getHttpClient() {
        if (null == httpClient) {
            HttpParams params = new BasicHttpParams();
            // 设置一些基本参数
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params,
                    "UTF-8");
            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, 1000);
            /* 请求超时 */
            HttpConnectionParams.setSoTimeout(params, 4000);
          
            // 设置我们的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;
    }
	
	/**
	 * 获得Post请求对象
	 * @param uri 请求地址,也可以带参数
	 * @param params 如果为null,则不添加由BasicNameValue封装的参数
	 * @return
	 */
	public static HttpPost getPost(String uri, List<BasicNameValuePair> params) {
		HttpPost post = new HttpPost(uri);
		try {
			if(params != null) {
				post.setEntity(new UrlEncodedFormEntity(params));
			}
		} catch (UnsupportedEncodingException e) { 
			e.printStackTrace();
		}
		return post;		
	}
	
	/**
	 * 用户使用的方法
	 * 功能:从服务器获得字符串
	 * @param post
	 * @return
	 */
	public static String getString(HttpPost post) {
		
		HttpClient httpClient = getHttpClient();
		HttpResponse response;
		try {
			response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				post.abort();
				Log.v(TAG, "响应失败,请求终止.");
				return null;
			} 
			Log.v(TAG, "响应成功.");
			return EntityUtils.toString(response.getEntity());
		} catch (ClientProtocolException e) { 
			e.printStackTrace();
			Log.e(TAG, e.getMessage());
			return null;
		} catch (IOException e) { 
			e.printStackTrace();
			Log.e(TAG, e.getMessage());
			return null;
		} 
	}
	
	/**
	 * 用户使用的方法
	 * 功能:请求服务器,返回字符串
	 * @param post post 请求对象
	 * @param requestLimit 请求失败限制次数
	 * @return
	 */
	public static String getString(HttpPost post, int requestLimit) {
		
		if (requestLimit < 1) {
			return null;
		}
		HttpResponse response;
		int currCount = 0; // 当前请求次数
		String result = null;
		
		while (currCount < requestLimit) {
			
			HttpClient httpClient = getHttpClient();
			currCount++;
			try {
				response = httpClient.execute(post);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					Log.v(TAG, "响应成功.");
					return EntityUtils.toString(response.getEntity());
				} else {
					post.abort();
					Log.v(TAG, "响应失败,请求终止."); 
					result = "响应失败,请求终止.";
				} 
			} catch (ClientProtocolException e) {  
				Log.e(TAG, e.getMessage());
				if (currCount > requestLimit) {
					result = "请求失败."; 
					break;
				} 
				System.out.println("ClientProtocolException");
			} catch (IOException e) {  
				Log.e(TAG, e.getMessage());
				if (e instanceof ConnectTimeoutException) {
					result = "连接超时.";
				} else {
					result = "IO异常.";
				}
				if (currCount > requestLimit) {	
					break;
				}
				System.out.println("IOException");
			} finally {
				System.out.println("finally"); 
			}
		}
		return result;
	}
	
	/**
	 * 用户使用的方法
	 * 功能:请求服务器,返回字符串
	 * @param uri 字符串形式的请求地址
	 * @param requestLimit 最多允许的请求失败次数
	 * @return
	 */
	public static String getString(String uri, int requestLimit) {   
		
		if (requestLimit < 1) {
			return null;
		}
		HttpResponse response;
		int currCount = 0; // 当前请求次数
		String result = null;
		HttpPost post = getPost(uri, null);
		while (currCount < requestLimit) {
			
			HttpClient httpClient = getHttpClient();
			currCount++;
			try {
				response = httpClient.execute(post);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					Log.v(TAG, "响应成功.");
					return EntityUtils.toString(response.getEntity());
				} else {
					post.abort();
					Log.v(TAG, "响应失败,请求终止."); 
					result = "响应失败,请求终止.";
				} 
			} catch (ClientProtocolException e) {  
				Log.e(TAG, e.getMessage());
				if (currCount > requestLimit) {
					result = "请求失败."; 
					break;
				} 
				System.out.println("ClientProtocolException");
			} catch (IOException e) {  
				//Log.e(TAG, e.getMessage());
				if (e instanceof ConnectTimeoutException) {
					result = "连接超时.";
				} else {
					result = "IO异常.";
				}
				if (currCount > requestLimit) {	
					break;
				}
				//System.out.println("IOException");
			} finally {
				System.out.println("finally"); 
			}
		}
		return result;
	}
	
	/**
	 * 释放建立http请求占用的资源
	 */
	public static void shutdown() { 
		// 释放建立http请求占用的资源
		httpClient.getConnectionManager().shutdown();
		httpClient = null;
	}
}

使用范例: 
package com.laili;

import java.util.ArrayList;
import java.util.List; 
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair; 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText; 
import com.laili.util.HttpUtil;

public class HttpUtilActivity extends Activity {
   
	private Button btn;
	private EditText show;
	private String uri = "http://10.2.105.76:8080/json/TestJsonServlet";
	private List<BasicNameValuePair> params;
    private Handler handler;
    private String showStr = "";
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        params = new ArrayList<BasicNameValuePair>();
        
        handler = new Handler() {
        	@Override
        	public void handleMessage(Message msg) {
        		switch (msg.what) {
        		case 0x01:
        			show.setText(showStr); 
        			break;
        		}
        	}
        };
        
        show = (EditText) findViewById(R.id.editText1);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new Thread(){
					public void run() { 
						params.add(new BasicNameValuePair("username", "zhelong"));
						params.add(new BasicNameValuePair("password", "123456"));
						HttpPost post = HttpUtil.getPost(uri, params);
						showStr += HttpUtil.getString(post,3); 
						//System.out.println(response);
						handler.sendEmptyMessage(0x01);
					};
				}.start();
			}
		});
    }
}



相关文章
|
4月前
|
Android开发
SharePreference封装成工具类
SharePreference封装成工具类
136 1
|
7月前
|
JSON 网络协议 C#
C# 工具类
C# 工具类
48 1
|
7月前
|
Java
JavaMap工具类(MapUtils)
JavaMap工具类(MapUtils)
|
数据采集 算法 安全
一天一个 JUC 工具类 -- 真工具类
CountDownLatch CyclicBarrier ForkJoin Semaphore 使用方法和注意事项
|
7月前
JsonUtil工具类
JsonUtil工具类
37 0
工具类-HttpClientUtil
工具类-HttpClientUtil
56 0
|
搜索推荐 安全 小程序
6个十分好用的工具类网站
6个十分好用的工具类网站
193 0
6个十分好用的工具类网站
|
Java API 索引
【JUC基础】08. 三大工具类
JUC包中包含了三个非常实用的工具类:CountDownLatch(倒计数器),CyclicBarrier(循环栅栏),Semaphore(信号量)。
148 0
|
安全
CollectionUtils工具类的常用方法
集合判断:   例1: 判断集合是否为空:  CollectionUtils.isEmpty(null): true  CollectionUtils.isEmpty(new ArrayList()): true    CollectionUtils.
2062 0