android獲取URLConnection和HttpClient網絡請求響應碼
https://www.open-open.com/lib/view/open1326868964593.html
有朋友問我網絡請求怎麼監聽超時,這個我當時也沒有沒有做過,就認為是try....catch...獲取異常,結果發現沒有獲取到,今天有時間,研究了一下,發現是從響應中來獲取的對象中獲取的,下麵我把自己寫的URLConnection和HttpClient網絡請求響應碼的實體共享給大家,希望對大家有幫助!
package com.zhangke.product.platform.http.json; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionRequest; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import com.zhangke.product.platform.util.NetworkUtil; import android.content.Context; import android.util.Log; /** * @author spring sky * QQ 840950105 * Email :vipa1888@163.com * 版權:spring sky * This class use in for request server and get server respnonse data * * */ public class NetWork { /** * 網絡請求響應碼 * <br> */ private int responseCode = 1; /** * 408為網絡超時 */ public static final int REQUEST_TIMEOUT_CODE = 408; /** * 請求字符編碼 */ private static final String CHARSET = "utf-8"; /** * 請求服務器超時時間 */ private static final int REQUEST_TIME_OUT = 1000*10; /** * 讀取響應的數據時間 */ private static final int READ_TIME_OUT = 1000*5; private Context context ; public NetWork(Context context) { super(); this.context = context; } /** * inputstream to String type * @param is * @return */ public String getString(InputStream is ) { String str = null; try { if(is!=null) { BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET)); String line = null; StringBuffer sb = new StringBuffer(); while((line=br.readLine())!=null) { sb.append(line); } str = sb.toString(); if(str.startsWith("<html>")) //獲取xml或者json數據,如果獲取到的數據為xml,則為null { str = null; } } } catch (Exception e) { e.printStackTrace(); } return str; } /** * httpClient request type * @param requestURL * @param map * @return */ public InputStream requestHTTPClient(String requestURL,Map<String, String> map) { InputStream inputStream = null; /** * 添加超時時間 */ BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIME_OUT); HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT); HttpClient httpClient = new DefaultHttpClient(httpParams); if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) { HttpHost proxy = new HttpHost("10.0.0.172", 80); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } HttpPost httpPost = new HttpPost(requestURL); httpPost.setHeader("Charset", CHARSET); httpPost.setHeader("Content-Type","application/x-www-form-urlencoded"); List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); Iterator<String> it = map.keySet().iterator(); while(it.hasNext()) { String key = it.next(); String value = map.get(key); Log.e("request server ", key+"="+value); list.add(new BasicNameValuePair(key, value)); } try { httpPost.setEntity(new UrlEncodedFormEntity(list,CHARSET)); HttpResponse response =httpClient.execute(httpPost); inputStream = response.getEntity().getContent(); responseCode = response.getStatusLine().getStatusCode(); //獲取響應碼 Log.e("response code", response.getStatusLine().getStatusCode()+""); // Header[] headers = response.getAllHeaders(); //獲取header中的數據 // for (int i = 0; i < headers.length; i++) { // Header h = headers[i]; // Log.e("request heads", h.getName()+"="+h.getValue()+" "); // } } catch (Exception e) { inputStream = null; e.printStackTrace(); } return inputStream; } /** * url request type * @param requestURL * @param map * @return */ public InputStream requestHTTPURL(String requestURL,Map<String,String> map ) { InputStream inputStream = null; URL url = null; URLConnection urlconn = null; HttpURLConnection conn = null; try { url = new URL(requestURL); if (NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) { Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("10.0.0.172", 80)); urlconn = url.openConnection(proxy); }else{ urlconn = url.openConnection(); } conn = (HttpURLConnection) urlconn; if(conn!=null) { conn.setReadTimeout(READ_TIME_OUT); conn.setConnectTimeout(REQUEST_TIME_OUT); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Charset", CHARSET); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); OutputStream os = conn.getOutputStream(); StringBuffer sb = new StringBuffer(); Iterator<String> it = map.keySet().iterator(); while(it.hasNext()) { String key = it.next(); String value = map.get(key); Log.e("request server ", key+"="+value); sb.append(key).append("=").append(value).append("&"); } String params = sb.toString().substring(0, sb.toString().length()-1); os.write(params.getBytes()); os.close(); inputStream = conn.getInputStream(); Log.e("response code", conn.getResponseCode()+""); responseCode = conn.getResponseCode(); //獲取響應碼 // Map<String, List<String>> headers = conn.getHeaderFields(); //獲取header中的數據 // Iterator<String> is = headers.keySet().iterator(); // while(is.hasNext()) // { // String key = is.next(); // List<String> values = headers.get(key); // String value = ""; // for (int i = 0; i < values.size(); i++) { // value+= values.get(i); // } // Log.e("request heads",key+"="+value+" "); // } } } catch (Exception e) { inputStream = null; e.printStackTrace(); } return inputStream; } /** * 網絡請求響應碼 */ public int getResponseCode() { return responseCode ; } }
最後更新:2017-04-03 19:13:18