android获取URLConnection和HttpClient网络请求响应码

来源:互联网 发布:java 滑动验证码 开源 编辑:程序博客网 时间:2024/05/21 07:52

android获取URLConnection和HttpClient网络请求响应码

转自:http://www.open-open.com/lib/view/open1326868964593.html 
前段时间,有朋友问我网络请求怎么监听超时,这个我当时也没有没有做过,就认为是try....catch...获取异常,结果发现没有获取到,今天有时间,研究了一下,发现是从响应中来获取的对象中获取的,下面我把自己写的URLConnection和HttpClient网络请求响应码的实体共享给大家,希望对大家有帮助!
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
packagecom.zhangke.product.platform.http.json;
 
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.UnsupportedEncodingException;
importjava.net.HttpURLConnection;
importjava.net.InetSocketAddress;
importjava.net.Proxy;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
 
importorg.apache.http.Header;
importorg.apache.http.HttpHost;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.conn.ClientConnectionRequest;
importorg.apache.http.conn.params.ConnRoutePNames;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.params.BasicHttpParams;
importorg.apache.http.params.HttpConnectionParams;
importorg.apache.http.params.HttpParams;
 
importcom.zhangke.product.platform.util.NetworkUtil;
 
importandroid.content.Context;
importandroid.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
 *
 *
 */
publicclass NetWork {
    /**
     *   网络请求响应码
     *   <br>
     */
    privateint responseCode = 1;
    /**
     *  408为网络超时
     */
    publicstatic final int REQUEST_TIMEOUT_CODE = 408;
     
    /**
     * 请求字符编码
     */
    privatestatic final String CHARSET = "utf-8";
    /**
     * 请求服务器超时时间
     */
    privatestatic final int REQUEST_TIME_OUT = 1000*10;
    /**
     * 读取响应的数据时间
     */
    privatestatic final int READ_TIME_OUT = 1000*5;
    privateContext context ;
     
    publicNetWork(Context context) {
        super();
        this.context = context;
    }
    /**
     * inputstream to String type
     * @param is
     * @return
     */
    publicString getString(InputStream is )
    {
        String str = null;
        try{
            if(is!=null)
            {
                BufferedReader br = newBufferedReader(newInputStreamReader(is, CHARSET));
                String line = null;
                StringBuffer sb = newStringBuffer();
                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();
        }
        returnstr;
    }
    /**
     * httpClient request type
     * @param requestURL
     * @param map
     * @return
     */
    publicInputStream requestHTTPClient(String requestURL,Map<String, String> map)
    {
        InputStream inputStream = null;
        /**
         * 添加超时时间
         */
        BasicHttpParams httpParams = newBasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIME_OUT);
        HttpConnectionParams.setSoTimeout(httpParams, READ_TIME_OUT);
        HttpClient httpClient = newDefaultHttpClient(httpParams);
         
        if(NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {
            HttpHost proxy = newHttpHost("10.0.0.172"80);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    proxy);
        }
         
        HttpPost httpPost = newHttpPost(requestURL);
        httpPost.setHeader("Charset", CHARSET);
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
        List<BasicNameValuePair> list = newArrayList<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(newBasicNameValuePair(key, value));
        }
        try{
            httpPost.setEntity(newUrlEncodedFormEntity(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();
        }
        returninputStream;
         
         
    }
    /**
     * url request type
     * @param requestURL
     * @param map
     * @return
     */
    publicInputStream requestHTTPURL(String requestURL,Map<String,String> map )
    {
        InputStream inputStream = null;
        URL url = null;
        URLConnection urlconn = null;
        HttpURLConnection conn = null;
        try{
            url = newURL(requestURL);
            if(NetworkUtil.getNetworkType() == NetworkUtil.WAP_CONNECTED) {
                Proxy proxy = newProxy(java.net.Proxy.Type.HTTP,
                        newInetSocketAddress("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 = newStringBuffer();
                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();
        }
        returninputStream;
    }
    /**
     *   网络请求响应码
     */
    publicint getResponseCode()
    {
        returnresponseCode ;
    }
     
     
}

0 0
原创粉丝点击