用httpclient-3.1 的android網絡通信

package cn.project.app.http;

import java.io.FileNotFoundException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;

import android.util.Log;

import com.google.gson.Gson;

import cn.uninor.app.bean.ErrorBean;
import cn.uninor.app.service.ErrorCodeService;
import cn.uninor.app.util.MyFileOut;

public class MyApachHttp {

	public static JSONObject getHttpJSONObject(String url){
		JSONObject object = null;
		String result = getHttpJson(url);
		try {
			if(result != null){
				object = new JSONObject(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return object;
	}
	public static JSONObject getHttpJSONObject(String url,String json){
		JSONObject object = null;
		String result = getHttpJson(url,json);
		try {
			if(result != null){
				object = new JSONObject(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	
	public static String getHttpJson(String url){//For Get
		String response = null;
		HttpClient client = new HttpClient();
		GetMethod getMethod =new GetMethod(url);
		try {
			getMethod.setRequestHeader("Content-Type", "application/json; charset=utf-8");
			getMethod.getParams().setContentCharset("utf-8");
			getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 1000*10);
			client.executeMethod(getMethod);
			int response_status = getMethod.getStatusCode();
			if(response_status == 200){
				ErrorCodeService.setStatusCode(200);
				response = getMethod.getResponseBodyAsString();
			}else if(response_status == 400){
				Gson gson = new Gson();
				String error = getMethod.getResponseBodyAsString();
				ErrorBean errorBean = gson.fromJson(error, ErrorBean.class);
				ErrorCodeService.setStatusCode(400);
				ErrorCodeService.setErrorBean(errorBean);
			}
		}catch(SocketTimeoutException ste){
			ErrorCodeService.setStatusCode(100);//超時異常
			ste.printStackTrace();
			Log.i("size","SocketTimeoutException");
		}catch (UnknownHostException ukhe) {
			// TODO: handle exception
			ErrorCodeService.setStatusCode(101);//主機不好可達異常
			ukhe.printStackTrace();
			Log.i("size","UnknownHostException");
		}catch (FileNotFoundException fe) {//路徑不可用異常
			// TODO: handle exception
			ErrorCodeService.setStatusCode(102);
			fe.printStackTrace();
			Log.i("size","FileNotFoundException");
		}
		catch (Exception e) {
			ErrorCodeService.setStatusCode(103);
			e.printStackTrace();
			Log.i("size","Exception");
		}finally{
			getMethod.releaseConnection();//釋放鏈接
		}
		return response;
	}
	
	/**
	 * For Post
	 * @param url
	 * @param map
	 * @return
	 */
	public static String getHttpJson(String url,String json){
		String response = null;
		HttpClient client = new HttpClient();;
		PostMethod postMethod = new PostMethod(url);
		try {
			postMethod.setRequestHeader("Content-Type", "application/json; charset=utf-8");
			postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 1000*10);
			
			ByteArrayRequestEntity entity = new ByteArrayRequestEntity(json.getBytes(), "UTF-8");
			postMethod.setRequestEntity(entity);
			
			client.executeMethod(postMethod);
			int status_code = postMethod.getStatusLine().getStatusCode();
			
			if(status_code == 200){
				ErrorCodeService.setStatusCode(200);
				response = postMethod.getResponseBodyAsString();
			}else if(status_code == 400){
				String error = postMethod.getResponseBodyAsString();
				Gson gson = new Gson();
				ErrorBean errorBean = gson.fromJson(error, ErrorBean.class);
				ErrorCodeService.setStatusCode(400);
				ErrorCodeService.setErrorBean(errorBean);
				MyFileOut.writeOutputStrem(error);
			}
		}catch (SocketTimeoutException ste) {
			ErrorCodeService.setStatusCode(100);
			ste.printStackTrace();
			Log.i("size","SocketTimeoutException");
		}catch (UnknownHostException ukhe) {
			// TODO: handle exception
			ErrorCodeService.setStatusCode(101);
			ukhe.printStackTrace();
			Log.i("size","UnknownHostException");
		}catch (FileNotFoundException fe) {
			ErrorCodeService.setStatusCode(102);
			fe.printStackTrace();
			Log.i("size","FileNotFoundException");
		}catch (Exception e) {
			ErrorCodeService.setStatusCode(103);
			e.printStackTrace();
			Log.i("size","Exception");
		}finally{
			postMethod.releaseConnection();
		}
		return response;
	}
	
	public static StringBuffer map2StringBuffer(Map<String, Object> params) {
		StringBuffer buf = new StringBuffer("");
		if (params != null && params.size() > 0) {
			Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, Object> entry = it.next();
				buf.append(entry.getKey()).append("=").append(entry.getValue()).toString();
				buf.append("&");
			}
		}
		if (buf.length() > 1)
			buf.deleteCharAt(buf.length() - 1);
		return buf;
	}
}


用Httpclient-3.1來網絡通信 

工具包下載:http://download.csdn.net/detail/wfung_kwok/4134264

新浪微博就是這樣個包來進行網絡通信的,個人在做項目過程中,用android自帶的網絡通信不知道為什麼,會出現亂碼,我寫的這個APP是繁體的,數據接口來自.net。所出現的亂碼不是全部亂碼,而是個別亂碼,後來就用第三方的包來進行網絡通信,發現問題解決了。

上面的這個類是本人寫的,大家可以直接拿來用

要注意的是

a.上面post方法的數據是json的。post的數據也不是key-value(a=b&b=c),而是直接把{"a":"b","b":"c"}post上去。

如果要post key=valus的話,用

NameValuePair[] pb = new NameValuePair[3];
pb[1] = new NameValuePair("a", "b");
postMethod.setRequestBody(pb);

b.上面get方法的話,這裏不做解釋了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章