- 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 :[email protected]
- 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 }
android獲取URLConnection和HttpClient網絡請求響應碼
前段時間,有朋友問我網絡請求怎麼監聽超時,這個我當時也沒有沒有做過,就認爲是try....catch...獲取異常,結果發現沒有獲取到,今天有時間,研究了一下,發現是從響應中來獲取的對象中獲取的,下面我把自己寫的URLConnection和HttpClient網絡請求響應碼的實體共享給大家,希望對大家有幫助!
相關熱門文章
給主人留下些什麼吧!~~
評論熱議
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.