前段时间,有朋友问我网络请求怎么监听超时,这个我当时也没有没有做过,就认为是try....catch...获取异常,结果发现没有获取到,今天有时间,研究了一下,发现是从响应中来获取的对象中获取的,下面我把自己写的URLConnection和HttpClient网络请求响应码的实体共享给大家,希望对大家有帮助!
- package com.zhangke.product.platform.http.json;
- 002
- 003 import java.io.BufferedReader;
- 004 import java.io.IOException;
- 005 import java.io.InputStream;
- 006 import java.io.InputStreamReader;
- 007 import java.io.OutputStream;
- 008 import java.io.UnsupportedEncodingException;
- 009 import java.net.HttpURLConnection;
- 010 import java.net.InetSocketAddress;
- 011 import java.net.Proxy;
- 012 import java.net.URL;
- 013 import java.net.URLConnection;
- 014 import java.util.ArrayList;
- 015 import java.util.Iterator;
- 016 import java.util.List;
- 017 import java.util.Map;
- 018
- 019 import org.apache.http.Header;
- 020 import org.apache.http.HttpHost;
- 021 import org.apache.http.HttpResponse;
- 022 import org.apache.http.client.ClientProtocolException;
- 023 import org.apache.http.client.HttpClient;
- 024 import org.apache.http.client.entity.UrlEncodedFormEntity;
- 025 import org.apache.http.client.methods.HttpPost;
- 026 import org.apache.http.conn.ClientConnectionRequest;
- 027 import org.apache.http.conn.params.ConnRoutePNames;
- 028 import org.apache.http.impl.client.DefaultHttpClient;
- 029 import org.apache.http.message.BasicNameValuePair;
- 030 import org.apache.http.params.BasicHttpParams;
- 031 import org.apache.http.params.HttpConnectionParams;
- 032 import org.apache.http.params.HttpParams;
- 033
- 034 import com.zhangke.product.platform.util.NetworkUtil;
- 035
- 036 import android.content.Context;
- 037 import android.util.Log;
- 038 /**
- 039 * @author spring sky
- 040 * QQ 840950105
- 041 * Email :vipa1888@163.com
- 042 * 版权:spring sky
- 043 * This class use in for request server and get server respnonse data
- 044 *
- 045 *
- 046 */
- 047 public class NetWork {
- 048 /**
- 049 * 网络请求响应码
- 050 * <br>
- 051 */
- 052 private int responseCode = 1;
- 053 /**
- 054 * 408为网络超时
- 055 */
- 056 public static final int REQUEST_TIMEOUT_CODE = 408;
- 057
- 058 /**
- 059 * 请求字符编码
- 060 */
- 061 private static final String CHARSET = "utf-8";
- 062 /**
- 063 * 请求服务器超时时间
- 064 */
- 065 private static final int REQUEST_TIME_OUT = 1000*10;
- 066 /**
- 067 * 读取响应的数据时间
- 068 */
- 069 private static final int READ_TIME_OUT = 1000*5;
- 070 private Context context ;
- 071
- 072 public NetWork(Context context) {
- 073 super();
- 074 this.context = context;
- 075 }
- 076 /**
- 077 * inputstream to String type
- 078 * @param is
- 079 * @return
- 080 */
- 081 public String getString(InputStream is )
- 082 {
- 083 String str = null;
- 084 try {
- 085 if(is!=null)
- 086 {
- 087 BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET));
- 088 String line = null;
- 089 StringBuffer sb = new StringBuffer();
- 090 while((line=br.readLine())!=null)
- 091 {
- 092 sb.append(line);
- 093 }
- 094 str = sb.toString();
- 095 if(str.startsWith("<html>")) //获取xml或者json数据,如果获取到的数据为xml,则为null
- 096 {
- 097 str = null;
- 098 }
- 099 }
- 100
- 101 } catch (Exception e) {
- 102 e.printStackTrace();
- 103 }
- 104 return str;
- 105 }
- 106 /**
- 107 * httpClient request type
- 108 * @param requestURL
- 109 * @param map
- 110 * @return
- 111 */
- 112 public InputStream requestHTTPClient(String requestURL,Map<String, String> map)
- 113 {
- 114 InputStream inputStream = null;
- 115 /**
- 116 * 添加超时时间
- 117 */
- 118 BasicHttpParams httpParams = new BasicHttpParams();
- 119 HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIME_OUT);
- 120 HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
- 121 HttpClient httpClient = new DefaultHttpClient(httpParams);
- 122
- 123 if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {
- 124 HttpHost proxy = new HttpHost("10.0.0.172", 80);
- 125 httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
- 126 proxy);
- 127 }
- 128
- 129 HttpPost httpPost = new HttpPost(requestURL);
- 130 httpPost.setHeader("Charset", CHARSET);
- 131 httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
- 132 List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
- 133 Iterator<String> it = map.keySet().iterator();
- 134 while(it.hasNext())
- 135 {
- 136 String key = it.next();
- 137 String value = map.get(key);
- 138 Log.e("request server ", key+"="+value);
- 139 list.add(new BasicNameValuePair(key, value));
- 140 }
- 141 try {
- 142 httpPost.setEntity(new UrlEncodedFormEntity(list,CHARSET));
- 143 HttpResponse response =httpClient.execute(httpPost);
- 144 inputStream = response.getEntity().getContent();
- 145 responseCode = response.getStatusLine().getStatusCode(); //获取响应码
- 146 Log.e("response code", response.getStatusLine().getStatusCode()+"");
- 147 // Header[] headers = response.getAllHeaders(); //获取header中的数据
- 148 // for (int i = 0; i < headers.length; i++) {
- 149 // Header h = headers[i];
- 150 // Log.e("request heads", h.getName()+"="+h.getValue()+" ");
- 151 // }
- 152 } catch (Exception e) {
- 153 inputStream = null;
- 154 e.printStackTrace();
- 155 }
- 156 return inputStream;
- 157
- 158
- 159 }
- 160 /**
- 161 * url request type
- 162 * @param requestURL
- 163 * @param map
- 164 * @return
- 165 */
- 166 public InputStream requestHTTPURL(String requestURL,Map<String,String> map )
- 167 {
- 168 InputStream inputStream = null;
- 169 URL url = null;
- 170 URLConnection urlconn = null;
- 171 HttpURLConnection conn = null;
- 172 try {
- 173 url = new URL(requestURL);
- 174 if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {
- 175 Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
- 176 new InetSocketAddress("10.0.0.172", 80));
- 177 urlconn = url.openConnection(proxy);
- 178 }else{
- 179 urlconn = url.openConnection();
- 180 }
- 181 conn = (HttpURLConnection) urlconn;
- 182 if(conn!=null)
- 183 {
- 184 conn.setReadTimeout(READ_TIME_OUT);
- 185 conn.setConnectTimeout(REQUEST_TIME_OUT);
- 186 conn.setDoInput(true);
- 187 conn.setDoOutput(true);
- 188 conn.setUseCaches(false);
- 189 conn.setRequestProperty("Charset", CHARSET);
- 190 conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
- 191 OutputStream os = conn.getOutputStream();
- 192 StringBuffer sb = new StringBuffer();
- 193 Iterator<String> it = map.keySet().iterator();
- 194 while(it.hasNext())
- 195 {
- 196 String key = it.next();
- 197 String value = map.get(key);
- 198 Log.e("request server ", key+"="+value);
- 199 sb.append(key).append("=").append(value).append("&");
- 200 }
- 201 String params = sb.toString().substring(0, sb.toString().length()-1);
- 202 os.write(params.getBytes());
- 203 os.close();
- 204 inputStream = conn.getInputStream();
- 205 Log.e("response code", conn.getResponseCode()+"");
- 206 responseCode = conn.getResponseCode(); //获取响应码
- 207 // Map<String, List<String>> headers = conn.getHeaderFields(); //获取header中的数据
- 208 // Iterator<String> is = headers.keySet().iterator();
- 209 // while(is.hasNext())
- 210 // {
- 211 // String key = is.next();
- 212 // List<String> values = headers.get(key);
- 213 // String value = "";
- 214 // for (int i = 0; i < values.size(); i++) {
- 215 // value+= values.get(i);
- 216 // }
- 217 // Log.e("request heads",key+"="+value+" ");
- 218 // }
- 219 }
- 220 } catch (Exception e) {
- 221 inputStream = null;
- 222 e.printStackTrace();
- 223 }
- 224 return inputStream;
- 225 }
- 226 /**
- 227 * 网络请求响应码
- 228 */
- 229 public int getResponseCode()
- 230 {
- 231 return responseCode ;
- 232 }
- 233
- 234
- 235 }
相关热门文章
给主人留下些什么吧!~~
评论热议