android的網絡訪問

1、核心類NetWorkCore,處理髮送請求

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * 網絡請求核心類,用於處理髮送請求和返回,單例
 * 
 * @author Administrator
 * 
 */
public class NetworkCore {
	//連接超時(ms)
	private static final int timeoutConnection = 30000;
	//響應超時(ms)
	private static final int timeoutSocket = 50000;

	private static NetworkCore instance;
	/*get請求*/
	private HttpGet httpGet;
	/*post請求*/
	private HttpPost httpPost;
	
	public static NetworkCore Instance() {
		if (instance == null) {
			instance = new NetworkCore();
		}
		return instance;
	}
	/**
	 * 發送請求
	 * @param request 請求線程對象
	 * @return 請求結果
	 */
	public NetWorkResponseMsg perform(DoRequestRunnable request) {
		NetWorkResponseMsg msg = null;
		NetworkRequestMsg mNetworkRequestMsg = request.getmNetworkRequestMsg();
		try {
			if (NetworkRequestMsg.POST.equals(mNetworkRequestMsg.getType())) {
				msg = handlePostRequest(mNetworkRequestMsg);
			} else {
				msg = handleGetRequest(mNetworkRequestMsg);
			}
			if (msg.getInputStream()==null) {
				msg.setResponseMsg(NetworkError.NODATA);
			}
			request.handleNetResponseMsg(msg);
		} catch (IOException e) {
			msg.setResponseMsg(NetworkError.CONNECT_ERROR);
		} finally {
			msg.closeStream();
		}
		return msg;
	}
	/**
	 * get請求
	 * @param mNetworkRequestMsg
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private NetWorkResponseMsg handleGetRequest(NetworkRequestMsg mNetworkRequestMsg)
			throws ClientProtocolException, IOException {
		InputStream is = null;
		StringBuffer finalURL = new StringBuffer(mNetworkRequestMsg.getUrl());
		int index = finalURL.indexOf("?");
		if (null != mNetworkRequestMsg.getParam()) {
			for (String paramName : mNetworkRequestMsg.getParam()
					.getParamNames()) {
				if (index == -1) {
					finalURL.append("?"
							+ paramName
							+ "="
							+ mNetworkRequestMsg.getParam().getParamValue(
									paramName));
				} else {
					finalURL.append("&"
							+ paramName
							+ "="
							+ mNetworkRequestMsg.getParam().getParamValue(
									paramName));
				}
				index++;
			}
			mNetworkRequestMsg.setUrl(finalURL.toString());
		}
		httpGet = new HttpGet(finalURL.toString());
		if (mNetworkRequestMsg.getParam().getParamNames().size() > 0) {
			for (String headerName : mNetworkRequestMsg.getParam()
					.getHeaderNames()) {
				httpGet.addHeader(headerName, mNetworkRequestMsg.getParam()
						.getHeaderValue(headerName));
			}
		}
		mNetworkRequestMsg.getParam().clearCache();
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		HttpClient httpclient = new DefaultHttpClient(httpParameters);
		if (mNetworkRequestMsg.isNeedProxy()) {
			String address = mNetworkRequestMsg.getProxyAddress() == null ? NetworkConfig.DEFAULT_PROXY
					: mNetworkRequestMsg.getProxyAddress();
			int port = mNetworkRequestMsg.getProxyPort() == 0 ? NetworkConfig.DEFAULT_PROXYPORT
					: mNetworkRequestMsg.getProxyPort();
			setProxy(httpclient, address, port);
		}
		HttpResponse httpResponse = httpclient.execute(httpGet);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			is = httpResponse.getEntity().getContent();
		} 
		return new NetWorkResponseMsg(is,httpResponse.getStatusLine().getStatusCode());
	}
	/**
	 * post請求
	 * @param mNetworkRequestMsg
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private NetWorkResponseMsg handlePostRequest(NetworkRequestMsg mNetworkRequestMsg)
			throws ClientProtocolException, IOException {
		InputStream is = null;
		HttpEntity httpentity = null;
		StringBuffer finalURL = new StringBuffer(mNetworkRequestMsg.getUrl());
		int index = finalURL.indexOf("?");
		if (null != mNetworkRequestMsg.getParam()) {
			for (String paramName : mNetworkRequestMsg.getParam()
					.getParamNames()) {
				if (index == -1) {
					finalURL.append("?"
							+ paramName
							+ "="
							+ mNetworkRequestMsg.getParam().getParamValue(
									paramName));
				} else {
					finalURL.append("&"
							+ paramName
							+ "="
							+ mNetworkRequestMsg.getParam().getParamValue(
									paramName));
				}
				index++;
			}
			mNetworkRequestMsg.setUrl(finalURL.toString());
		}
		httpPost = new HttpPost(finalURL.toString());
		if (mNetworkRequestMsg.getParam().getParamNames().size() > 0) {
			for (String headerName : mNetworkRequestMsg.getParam()
					.getHeaderNames()) {
				httpPost.addHeader(headerName, mNetworkRequestMsg.getParam()
						.getHeaderValue(headerName));
			}
		}
		mNetworkRequestMsg.getParam().clearCache();
		if (mNetworkRequestMsg.getParam().getArrayBody() != null) {
			httpentity = new ByteArrayEntity(mNetworkRequestMsg.getParam()
					.getArrayBody());
		} else if (mNetworkRequestMsg.getParam().getBody() != null) {
			httpentity = new StringEntity(mNetworkRequestMsg.getParam()
					.getBody());
		}
		if (null != httpentity) {
			httpPost.setEntity(httpentity);
		}
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient httpclient = new DefaultHttpClient(httpParameters);
		if (mNetworkRequestMsg.isNeedProxy()) {
			String address = mNetworkRequestMsg.getProxyAddress() == null ? NetworkConfig.DEFAULT_PROXY
					: mNetworkRequestMsg.getProxyAddress();
			int port = mNetworkRequestMsg.getProxyPort() == 0 ? NetworkConfig.DEFAULT_PROXYPORT
					: mNetworkRequestMsg.getProxyPort();
			setProxy(httpclient, address, port);
		}
		HttpResponse httpResponse = httpclient.execute(httpPost);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			is = httpResponse.getEntity().getContent();
		}
		return new NetWorkResponseMsg(is,httpResponse.getStatusLine().getStatusCode());
	}
	/**
	 * 斷開連接
	 */
	public void abort(){
		if(httpGet != null){
			if(!httpGet.isAborted()){
				httpGet.abort();
			}
		}
		if(httpPost != null){
			if(!httpPost.isAborted()){
				httpPost.abort();
			}
		}
	}
	/**
	 * 
	 * @param httpclient
	 * @param address
	 * @param port
	 */
	private void setProxy(HttpClient httpclient, String address, int port) {
		HttpHost proxy = new HttpHost(address, port);
		httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
				proxy);
	}

}

2、請求封裝類NetworkRequestMsg:

public class NetworkRequestMsg extends Message {
	
	public static final String GET = "GET";
	public static final String POST = "POST";
	

	/**
	 * 產生自增ID計數器
	 */
	private static short ID = 0;

	/**
	 * 當前消息id
	 */
	private short id = 0;

	/**
	 * 當前請求類型(GET/POST)
	 */
	private String type;

	/**
	 * 請求地址URL
	 */
	private String url;

	/**
	 * 請求消息參數
	 */
	private Parameter param;

	/**
	 * 數據連接返回值
	 */
	private byte retcode = -1;

	/**
	 * 請求是否取消
	 */
	private boolean cancel = false;

	/**
	 * 是否正在發送數據
	 */
	private boolean sending = false;

	/**
	 * 是否是下載類型
	 */
	private boolean download = false;

	/**
	 * 重發次數
	 */
	private byte sendTime = 0;
	
	/**
	 * 網絡數據解析協議
	 */
	private String protocol;
	
	/**
	 * 是否需要代理
	 */
	private boolean isNeedProxy;
	
	/**
	 * 代理地址
	 */
	private String proxyAddress;
	
	
	/**
	 * 代理端口
	 */
	private int proxyPort; 

	
	

	public NetworkRequestMsg(String _url,String _type ,Parameter _param,boolean isNeedProxy,String _proxyAddress,int _proxyPort){
		
		this.url = _url;
		this.type = _type;
		this.isNeedProxy = isNeedProxy;
		this.param = _param;
		this.proxyAddress = _proxyAddress;
		this.proxyPort = _proxyPort;
		
	}
	

	public static short getID() {
		return ID;
	}

	public static void setID(short iD) {
		ID = iD;
	}

	public short getId() {
		return id;
	}

	public void setId(short id) {
		this.id = id;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public byte getRetcode() {
		return retcode;
	}

	public void setRetcode(byte retcode) {
		this.retcode = retcode;
	}

	public boolean isCancel() {
		return cancel;
	}

	public void setCancel(boolean cancel) {
		this.cancel = cancel;
	}

	public boolean isSending() {
		return sending;
	}

	public void setSending(boolean sending) {
		this.sending = sending;
	}

	public boolean isDownload() {
		return download;
	}

	public void setDownload(boolean download) {
		this.download = download;
	}

	public byte getSendTime() {
		return sendTime;
	}

	public void setSendTime(byte sendTime) {
		this.sendTime = sendTime;
	}
	public Parameter getParam() {
		return param;
	}


	public void setParam(Parameter param) {
		this.param = param;
	}


	
	
	
	
	public String getProtocol() {
		return protocol;
	}


	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}


	public boolean isNeedProxy() {
		return isNeedProxy;
	}


	public void setNeedProxy(boolean isNeedProxy) {
		this.isNeedProxy = isNeedProxy;
	}
	
	public String getProxyAddress() {
		return proxyAddress;
	}

	public void setProxyAddress(String proxyAddress) {
		this.proxyAddress = proxyAddress;
	}

	public int getProxyPort() {
		return proxyPort;
	}

	public void setProxyPort(int proxyPort) {
		this.proxyPort = proxyPort;
	}
}

請求參數封裝類Parameter:

import java.util.ArrayList;
import java.util.HashMap;

public class Parameter {
	
	private HashMap<String,String> header = new HashMap<String,String>();
	private ArrayList<String> allHeaderNames = new ArrayList<String>();
	//參數信息
	private HashMap<String,String> param = new HashMap<String,String>();
	private ArrayList<String> allParamNames = new ArrayList<String>();
	//實體信息
	private String body;
	
	private byte[] arrayBody;
	
	public String getParamValue(String _name){
		return param.get(_name);
	}
	public String getHeaderValue(String _name){
		return header.get(_name);
	}
	
	public void addHeader(String _name,String _value) throws Exception{
		if(null != _name && null != _value ){
			header.put(_name, _value);
			allHeaderNames.add(_name);
		} else {
			throw new Exception("頭信息請求參數非法");
		}
	}
	
	public void addParam(String _name,String _value) throws Exception{
		if(null != _name && null != _value ){
			param.put(_name, _value);
			allParamNames.add(_name);
		} else {
			throw new Exception("請求參數非法");
		}
	}
	
	
	public ArrayList<String> getHeaderNames(){
		return allHeaderNames;
	}
	public  ArrayList<String> getParamNames(){
		return allParamNames;
	}
	
	public void clearCache(){
		if(null != header){
			header.clear();
		}
		if(null != allHeaderNames){
			allHeaderNames.clear();
		}
		if(null != param){
			param.clear();
		}
		if(null != allParamNames){
			allParamNames.clear();
		}
		
	}
	
	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	
	public byte[] getArrayBody() {
		return arrayBody;
	}
	public void setArrayBody(byte[] arrayBody) {
		this.arrayBody = arrayBody;
	}
	public Parameter(){
		clearCache();
	}
	

}

3 響應請求封裝類NetWorkResponseMsg:
import java.io.IOException;
import java.io.InputStream;

public class NetWorkResponseMsg {
	
	private InputStream inputStream ;
	
	private int responseCode = 200;

	private String responseMsg = null;
	
	public NetWorkResponseMsg() {
	}

	
	public NetWorkResponseMsg(InputStream inputStream, int responseCode) {
		this.inputStream = inputStream;
		this.responseCode = responseCode;
	}

	
	public NetWorkResponseMsg(InputStream inputStream, int responseCode,
			String responseMsg) {
		this.inputStream = inputStream;
		this.responseCode = responseCode;
		this.responseMsg = responseMsg;
	}

	public String getResponseMsg() {
		return responseMsg;
	}

	public void setResponseMsg(String responseMsg) {
		this.responseMsg = responseMsg;
	}


	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public int getResponseCode() {
		return responseCode;
	}

	public void setResponseCode(int responseCode) {
		this.responseCode = responseCode;
	}
	
	public void closeStream(){
		try {
			if(inputStream != null){
				inputStream.close();
			}
		} catch (IOException e) {
		}
	}
	
}


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