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); } }
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; } }
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(); } }
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) { } } }