android獲取URLConnection和HttpClient網絡請求響應碼

 前段時間,有朋友問我網絡請求怎麼監聽超時,這個我當時也沒有沒有做過,就認爲是try....catch...獲取異常,結果發現沒有獲取到,今天有時間,研究了一下,發現是從響應中來獲取的對象中獲取的,下面我把自己寫的URLConnection和HttpClient網絡請求響應碼的實體共享給大家,希望對大家有幫助!
  1. package com.zhangke.product.platform.http.json;

  2. 002

  3. 003 import java.io.BufferedReader;

  4. 004 import java.io.IOException;

  5. 005 import java.io.InputStream;

  6. 006 import java.io.InputStreamReader;

  7. 007 import java.io.OutputStream;

  8. 008 import java.io.UnsupportedEncodingException;

  9. 009 import java.net.HttpURLConnection;

  10. 010 import java.net.InetSocketAddress;

  11. 011 import java.net.Proxy;

  12. 012 import java.net.URL;

  13. 013 import java.net.URLConnection;

  14. 014 import java.util.ArrayList;

  15. 015 import java.util.Iterator;

  16. 016 import java.util.List;

  17. 017 import java.util.Map;

  18. 018

  19. 019 import org.apache.http.Header;

  20. 020 import org.apache.http.HttpHost;

  21. 021 import org.apache.http.HttpResponse;

  22. 022 import org.apache.http.client.ClientProtocolException;

  23. 023 import org.apache.http.client.HttpClient;

  24. 024 import org.apache.http.client.entity.UrlEncodedFormEntity;

  25. 025 import org.apache.http.client.methods.HttpPost;

  26. 026 import org.apache.http.conn.ClientConnectionRequest;

  27. 027 import org.apache.http.conn.params.ConnRoutePNames;

  28. 028 import org.apache.http.impl.client.DefaultHttpClient;

  29. 029 import org.apache.http.message.BasicNameValuePair;

  30. 030 import org.apache.http.params.BasicHttpParams;

  31. 031 import org.apache.http.params.HttpConnectionParams;

  32. 032 import org.apache.http.params.HttpParams;

  33. 033

  34. 034 import com.zhangke.product.platform.util.NetworkUtil;

  35. 035

  36. 036 import android.content.Context;

  37. 037 import android.util.Log;

  38. 038 /**

  39. 039 * @author spring sky

  40. 040 * QQ 840950105

  41. 041 * Email :[email protected]

  42. 042 * 版權:spring sky

  43. 043 * This class use in for request server and get server respnonse data

  44. 044 *

  45. 045 *

  46. 046 */

  47. 047 public class NetWork {

  48. 048 /**

  49. 049 * 網絡請求響應碼

  50. 050 * <br>

  51. 051 */

  52. 052 private int responseCode = 1;

  53. 053 /**

  54. 054 * 408爲網絡超時

  55. 055 */

  56. 056 public static final int REQUEST_TIMEOUT_CODE = 408;

  57. 057

  58. 058 /**

  59. 059 * 請求字符編碼

  60. 060 */

  61. 061 private static final String CHARSET = "utf-8";

  62. 062 /**

  63. 063 * 請求服務器超時時間

  64. 064 */

  65. 065 private static final int REQUEST_TIME_OUT = 1000*10;

  66. 066 /**

  67. 067 * 讀取響應的數據時間

  68. 068 */

  69. 069 private static final int READ_TIME_OUT = 1000*5;

  70. 070 private Context context ;

  71. 071

  72. 072 public NetWork(Context context) {

  73. 073 super();

  74. 074 this.context = context;

  75. 075 }

  76. 076 /**

  77. 077 * inputstream to String type

  78. 078 * @param is

  79. 079 * @return

  80. 080 */

  81. 081 public String getString(InputStream is )

  82. 082 {

  83. 083 String str = null;

  84. 084 try {

  85. 085 if(is!=null)

  86. 086 {

  87. 087 BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET));

  88. 088 String line = null;

  89. 089 StringBuffer sb = new StringBuffer();

  90. 090 while((line=br.readLine())!=null)

  91. 091 {

  92. 092 sb.append(line);

  93. 093 }

  94. 094 str = sb.toString();

  95. 095 if(str.startsWith("<html>")) //獲取xml或者json數據,如果獲取到的數據爲xml,則爲null


  96. 096 {

  97. 097 str = null;

  98. 098 }

  99. 099 }

  100. 100

  101. 101 } catch (Exception e) {

  102. 102 e.printStackTrace();

  103. 103 }

  104. 104 return str;

  105. 105 }

  106. 106 /**

  107. 107 * httpClient request type

  108. 108 * @param requestURL

  109. 109 * @param map

  110. 110 * @return

  111. 111 */

  112. 112 public InputStream requestHTTPClient(String requestURL,Map<String, String> map)

  113. 113 {

  114. 114 InputStream inputStream = null;

  115. 115 /**

  116. 116 * 添加超時時間

  117. 117 */

  118. 118 BasicHttpParams httpParams = new BasicHttpParams();

  119. 119 HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIME_OUT);

  120. 120 HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);

  121. 121 HttpClient httpClient = new DefaultHttpClient(httpParams);

  122. 122

  123. 123 if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {

  124. 124 HttpHost proxy = new HttpHost("10.0.0.172", 80);

  125. 125 httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,

  126. 126 proxy);

  127. 127 }

  128. 128

  129. 129 HttpPost httpPost = new HttpPost(requestURL);

  130. 130 httpPost.setHeader("Charset", CHARSET);

  131. 131 httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");

  132. 132 List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

  133. 133 Iterator<String> it = map.keySet().iterator();

  134. 134 while(it.hasNext())

  135. 135 {

  136. 136 String key = it.next();

  137. 137 String value = map.get(key);

  138. 138 Log.e("request server ", key+"="+value);

  139. 139 list.add(new BasicNameValuePair(key, value));

  140. 140 }

  141. 141 try {

  142. 142 httpPost.setEntity(new UrlEncodedFormEntity(list,CHARSET));

  143. 143 HttpResponse response =httpClient.execute(httpPost);

  144. 144 inputStream = response.getEntity().getContent();

  145. 145 responseCode = response.getStatusLine().getStatusCode(); //獲取響應碼


  146. 146 Log.e("response code", response.getStatusLine().getStatusCode()+"");

  147. 147 // Header[] headers = response.getAllHeaders(); //獲取header中的數據


  148. 148 // for (int i = 0; i < headers.length; i++) {


  149. 149 // Header h = headers[i];


  150. 150 // Log.e("request heads", h.getName()+"="+h.getValue()+" ");


  151. 151 // }


  152. 152 } catch (Exception e) {

  153. 153 inputStream = null;

  154. 154 e.printStackTrace();

  155. 155 }

  156. 156 return inputStream;

  157. 157

  158. 158

  159. 159 }

  160. 160 /**

  161. 161 * url request type

  162. 162 * @param requestURL

  163. 163 * @param map

  164. 164 * @return

  165. 165 */

  166. 166 public InputStream requestHTTPURL(String requestURL,Map<String,String> map )

  167. 167 {

  168. 168 InputStream inputStream = null;

  169. 169 URL url = null;

  170. 170 URLConnection urlconn = null;

  171. 171 HttpURLConnection conn = null;

  172. 172 try {

  173. 173 url = new URL(requestURL);

  174. 174 if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {

  175. 175 Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,

  176. 176 new InetSocketAddress("10.0.0.172", 80));

  177. 177 urlconn = url.openConnection(proxy);

  178. 178 }else{

  179. 179 urlconn = url.openConnection();

  180. 180 }

  181. 181 conn = (HttpURLConnection) urlconn;

  182. 182 if(conn!=null)

  183. 183 {

  184. 184 conn.setReadTimeout(READ_TIME_OUT);

  185. 185 conn.setConnectTimeout(REQUEST_TIME_OUT);

  186. 186 conn.setDoInput(true);

  187. 187 conn.setDoOutput(true);

  188. 188 conn.setUseCaches(false);

  189. 189 conn.setRequestProperty("Charset", CHARSET);

  190. 190 conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

  191. 191 OutputStream os = conn.getOutputStream();

  192. 192 StringBuffer sb = new StringBuffer();

  193. 193 Iterator<String> it = map.keySet().iterator();

  194. 194 while(it.hasNext())

  195. 195 {

  196. 196 String key = it.next();

  197. 197 String value = map.get(key);

  198. 198 Log.e("request server ", key+"="+value);

  199. 199 sb.append(key).append("=").append(value).append("&");

  200. 200 }

  201. 201 String params = sb.toString().substring(0, sb.toString().length()-1);

  202. 202 os.write(params.getBytes());

  203. 203 os.close();

  204. 204 inputStream = conn.getInputStream();

  205. 205 Log.e("response code", conn.getResponseCode()+"");

  206. 206 responseCode = conn.getResponseCode(); //獲取響應碼


  207. 207 // Map<String, List<String>> headers = conn.getHeaderFields(); //獲取header中的數據


  208. 208 // Iterator<String> is = headers.keySet().iterator();


  209. 209 // while(is.hasNext())


  210. 210 // {


  211. 211 // String key = is.next();


  212. 212 // List<String> values = headers.get(key);


  213. 213 // String value = "";


  214. 214 // for (int i = 0; i < values.size(); i++) {


  215. 215 // value+= values.get(i);


  216. 216 // }


  217. 217 // Log.e("request heads",key+"="+value+" ");


  218. 218 // }


  219. 219 }

  220. 220 } catch (Exception e) {

  221. 221 inputStream = null;

  222. 222 e.printStackTrace();

  223. 223 }

  224. 224 return inputStream;

  225. 225 }

  226. 226 /**

  227. 227 * 網絡請求響應碼

  228. 228 */

  229. 229 public int getResponseCode()

  230. 230 {

  231. 231 return responseCode ;

  232. 232 }

  233. 233

  234. 234

  235. 235 }
<script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/buttonLite.js#style=-1&uuid=&pophcol=3&lang=zh"></script> <script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/bshareC0.js"></script>
閱讀(1198) | 評論(0) | 轉發(0) |
給主人留下些什麼吧!~~
評論熱議
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章