HttpClient4.3 第二次封装

httpclient.java

?
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
package  com.httpclint.util;
 
import  java.io.File;
import  java.io.IOException;
import  java.util.HashMap;
import  java.util.Iterator;
import  java.util.Map;
 
import  org.apache.http.HttpException;
import  org.apache.http.entity.mime.content.ByteArrayBody;
import  org.apache.http.entity.mime.content.FileBody;
 
/**
  * HTTP工具类,封装HttpClient4.3.x来对外提供简化的HTTP请求
  * @author   yangjian1004
  * @Date     Aug 5, 2014     
  */
public  class  HttpClient {
 
     private  HttpProxy proxy;
 
     /**
      * 设置代理访问网络
      * @param proxy
      */
     public  void  setProxy(HttpProxy proxy) {
         this .proxy = proxy;
     }
 
     /**
      * 是否启用SSL模式
      * @param enabled
      */
     public  void  enableSSL( boolean  enabled) {
         HttpClientWrapper.enabledSSL(enabled);
     }
 
     /**
      * 使用Get方式 根据URL地址,获取ResponseStatus对象
     
      * @param url
      *            完整的URL地址
      * @return ResponseStatus 如果发生异常则返回null,否则返回ResponseStatus对象
      * @throws IOException 
      * @throws HttpException 
      */
     public  ResponseStatus get(String url)  throws  HttpException, IOException {
         HttpClientWrapper hw =  new  HttpClientWrapper(proxy);
         return  hw.sendRequest(url);
     }
 
     /**
      * 使用Get方式 根据URL地址,获取ResponseStatus对象
     
      * @param url
      *            完整的URL地址
      * @param urlEncoding
      *            编码,可以为null
      * @return ResponseStatus 如果发生异常则返回null,否则返回ResponseStatus对象
      */
     public  ResponseStatus get(String url, String urlEncoding) {
         HttpClientWrapper hw =  new  HttpClientWrapper(proxy);
         ResponseStatus response =  null ;
         try  {
             response = hw.sendRequest(url, urlEncoding);
         catch  (Exception e) {
             e.printStackTrace();
         }
         return  response;
     }
 
     /**
      * 将参数拼装在url中,进行post请求。
     
      * @param url
      * @return
      */
     public  ResponseStatus post(String url) {
         HttpClientWrapper hw =  new  HttpClientWrapper(proxy);
         ResponseStatus ret =  null ;
         try  {
             setParams(url, hw);
             ret = hw.postNV(url);
         catch  (Exception e) {
             e.printStackTrace();
         }
         return  ret;
     }
 
     private  void  setParams(String url, HttpClientWrapper hw) {
         String[] paramStr = url.split( "[?]" 2 );
         if  (paramStr ==  null  || paramStr.length !=  2 ) {
             return ;
         }
         String[] paramArray = paramStr[ 1 ].split( "[&]" );
         if  (paramArray ==  null ) {
             return ;
         }
         for  (String param : paramArray) {
             if  (param ==  null  ||  "" .equals(param.trim())) {
                 continue ;
             }
             String[] keyValue = param.split( "[=]" 2 );
             if  (keyValue ==  null  || keyValue.length !=  2 ) {
                 continue ;
             }
             hw.addNV(keyValue[ 0 ], keyValue[ 1 ]);
         }
     }
 
     /**
      * 上传文件(包括图片)
     
      * @param url
      *            请求URL
      * @param paramsMap
      *            参数和值
      * @return
      */
     public  ResponseStatus post(String url, Map<String, Object> paramsMap) {
         HttpClientWrapper hw =  new  HttpClientWrapper(proxy);
         ResponseStatus ret =  null ;
         try  {
             setParams(url, hw);
             Iterator<String> iterator = paramsMap.keySet().iterator();
             while  (iterator.hasNext()) {
                 String key = iterator.next();
                 Object value = paramsMap.get(key);
                 if  (value  instanceof  File) {
                     FileBody fileBody =  new  FileBody((File) value);
                     hw.getContentBodies().add(fileBody);
                 else  if  (value  instanceof  byte []) {
                     byte [] byteVlue = ( byte []) value;
                     ByteArrayBody byteArrayBody =  new  ByteArrayBody(byteVlue, key);
                     hw.getContentBodies().add(byteArrayBody);
                 else  {
                     if  (value !=  null  && ! "" .equals(value)) {
                         hw.addNV(key, String.valueOf(value));
                     else  {
                         hw.addNV(key,  "" );
                     }
                 }
             }
             ret = hw.postEntity(url);
         catch  (Exception e) {
             e.printStackTrace();
         }
         return  ret;
     }
 
     /**
      * 使用post方式,发布对象转成的json给Rest服务。
     
      * @param url
      * @param jsonBody
      * @return
      */
     public  ResponseStatus post(String url, String jsonBody) {
         return  post(url, jsonBody,  "application/json" );
     }
 
     /**
      * 使用post方式,发布对象转成的xml给Rest服务
     
      * @param url
      *            URL地址
      * @param xmlBody
      *            xml文本字符串
      * @return ResponseStatus 如果发生异常则返回空,否则返回ResponseStatus对象
      */
     public  ResponseStatus postXml(String url, String xmlBody) {
         return  post(url, xmlBody,  "application/xml" );
     }
 
     private  ResponseStatus post(String url, String body, String contentType) {
         HttpClientWrapper hw =  new  HttpClientWrapper(proxy);
         ResponseStatus ret =  null ;
         try  {
             hw.addNV( "body" , body);
             ret = hw.postNV(url, contentType);
         catch  (Exception e) {
             e.printStackTrace();
         }
         return  ret;
     }
 
     public  static  void  main(String[] args)  throws  HttpException, IOException {
         testGet();
         //testUploadFile();
     }
 
     //test
     public  static  void  testGet()  throws  HttpException, IOException {
         String url =  "http://www.baidu.com/" ;
         HttpClient c =  new  HttpClient();
         ResponseStatus r = c.get(url);
         System.out.println(r.getContent());
     }
 
     //test
     public  static  void  testUploadFile() {
         try  {
             HttpClient c =  new  HttpClient();
             String url =  "http://localhost:8280/jfly/action/admin/user/upload.do" ;
             Map<String, Object> paramsMap =  new  HashMap<String, Object>();
             paramsMap.put( "userName" "jj" );
             paramsMap.put( "password" "jj" );
             paramsMap.put( "filePath" new  File( "C:\\Users\\yangjian1004\\Pictures\\default (1).jpeg" ));
             ResponseStatus ret = c.post(url, paramsMap);
             System.out.println(ret.getContent());
         catch  (Exception e) {
             e.printStackTrace();
         }
     }
}
?
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package  com.httpclint.util;
 
import  java.io.IOException;
import  java.net.URLEncoder;
import  java.nio.charset.CodingErrorAction;
import  java.security.KeyManagementException;
import  java.security.NoSuchAlgorithmException;
import  java.security.cert.CertificateException;
import  java.security.cert.X509Certificate;
import  java.util.ArrayList;
import  java.util.Collections;
import  java.util.HashSet;
import  java.util.Iterator;
import  java.util.LinkedList;
import  java.util.List;
import  java.util.Set;
 
import  javax.net.ssl.SSLContext;
import  javax.net.ssl.TrustManager;
import  javax.net.ssl.X509TrustManager;
 
import  org.apache.http.Consts;
import  org.apache.http.Header;
import  org.apache.http.HeaderElement;
import  org.apache.http.HttpEntity;
import  org.apache.http.HttpException;
import  org.apache.http.HttpHeaders;
import  org.apache.http.HttpHost;
import  org.apache.http.NameValuePair;
import  org.apache.http.StatusLine;
import  org.apache.http.auth.AuthScope;
import  org.apache.http.auth.UsernamePasswordCredentials;
import  org.apache.http.client.CredentialsProvider;
import  org.apache.http.client.entity.UrlEncodedFormEntity;
import  org.apache.http.client.methods.CloseableHttpResponse;
import  org.apache.http.client.methods.HttpGet;
import  org.apache.http.client.methods.HttpPost;
import  org.apache.http.client.methods.HttpRequestBase;
import  org.apache.http.config.ConnectionConfig;
import  org.apache.http.config.MessageConstraints;
import  org.apache.http.config.Registry;
import  org.apache.http.config.RegistryBuilder;
import  org.apache.http.config.SocketConfig;
import  org.apache.http.conn.socket.ConnectionSocketFactory;
import  org.apache.http.conn.socket.PlainConnectionSocketFactory;
import  org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import  org.apache.http.conn.ssl.SSLContexts;
import  org.apache.http.entity.ContentType;
import  org.apache.http.entity.mime.HttpMultipartMode;
import  org.apache.http.entity.mime.MultipartEntityBuilder;
import  org.apache.http.entity.mime.content.ContentBody;
import  org.apache.http.entity.mime.content.StringBody;
import  org.apache.http.impl.client.BasicCredentialsProvider;
import  org.apache.http.impl.client.CloseableHttpClient;
import  org.apache.http.impl.client.HttpClients;
import  org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import  org.apache.http.message.BasicNameValuePair;
import  org.apache.http.util.CharsetUtils;
import  org.apache.http.util.EntityUtils;
 
/**
  * 封装HttpClient
  * <p>
  * @author   yangjian1004
  * @Date     Aug 5, 2014     
  */
public  class  HttpClientWrapper {
 
     private  enum  HttpMethod {
         GET, POST
     }
 
     private  static  CloseableHttpClient client;
     private  List<ContentBody> contentBodies;
     private  List<NameValuePair> nameValuePostBodies;
     private  static  PoolingHttpClientConnectionManager connManager =  null ;
     
     
     public  static  void  enabledSSL( boolean  enabled) {
         if  (enabled) {
             try  {
                 SSLContext sslContext = SSLContexts.custom().useTLS().build();
                 sslContext.init( null new  TrustManager[] {  new  X509TrustManager() {
 
                     public  void  checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                             throws  CertificateException {
                     }
 
                     public  void  checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                             throws  CertificateException {
                     }
 
                     public  X509Certificate[] getAcceptedIssuers() {
                         return  null ;
                     }
                 } },  null );
                 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                         .<ConnectionSocketFactory> create().register( "http" , PlainConnectionSocketFactory.INSTANCE)
                         .register( "https" new  SSLConnectionSocketFactory(sslContext)).build();
                 connManager =  new  PoolingHttpClientConnectionManager(socketFactoryRegistry);
                 SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay( true ).build();
                 connManager.setDefaultSocketConfig(socketConfig);
                 MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount( 200 )
                         .setMaxLineLength( 2000 ).build();
                 
                 ConnectionConfig connectionConfig = ConnectionConfig.custom()
                         .setMalformedInputAction(CodingErrorAction.IGNORE)
                         .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
                         .setMessageConstraints(messageConstraints).build();
                 connManager.setDefaultConnectionConfig(connectionConfig);
                 connManager.setMaxTotal( 200 );
                 connManager.setDefaultMaxPerRoute( 20 );
             catch  (KeyManagementException e) {
 
             catch  (NoSuchAlgorithmException e) {
 
             }
         }
     }
 
     public  HttpClientWrapper(HttpProxy proxy) {
         super ();
         //client                 = HttpClientBuilder.create().build();//不使用连接池
         client =  this .getCloseableHttpClient(proxy);
         this .contentBodies =  new  ArrayList<ContentBody>();
         this .nameValuePostBodies =  new  LinkedList<NameValuePair>();
     }
 
     private  CloseableHttpClient getCloseableHttpClient(HttpProxy proxy) {
         if  ( null  != proxy) {
             HttpHost proxyHost =  new  HttpHost(proxy.getHost(), proxy.getPort());
             CredentialsProvider credentialsProvider =  new  BasicCredentialsProvider();
             if  ( null  != proxy.getUser() &&  null  != proxy.getPassword()) {
                 credentialsProvider.setCredentials( new  AuthScope(proxy.getHost(), proxy.getPort()),
                         new  UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()));
             }
             return  HttpClients.custom().setProxy(proxyHost).setDefaultCredentialsProvider(credentialsProvider).build();
         else  {
             return  HttpClients.custom().setConnectionManager(connManager).build();
         }
     }
 
     /**
      * Get方式访问URL
     
      * @param url
      * @return
      * @throws HttpException
      * @throws IOException
      */
     public  ResponseStatus sendRequest(String url)  throws  HttpException, IOException {
         return  this .sendRequest(url,  "UTF-8" , HttpMethod.GET,  null );
     }
 
     /**
      * Get方式访问URL
     
      * @param url
      * @param urlEncoding
      * @return
      * @throws HttpException
      * @throws IOException
      */
     public  ResponseStatus sendRequest(String url, String urlEncoding)  throws  HttpException, IOException {
         return  this .sendRequest(url, urlEncoding, HttpMethod.GET,  null );
     }
 
     /**
      * POST方式发送名值对请求URL
     
      * @param url
      * @return
      * @throws HttpException
      * @throws IOException
      */
     public  ResponseStatus postNV(String url)  throws  HttpException, IOException {
         return  this .sendRequest(url,  "UTF-8" , HttpMethod.POST,  null );
     }
 
     public  ResponseStatus postNV(String url, String contentType)  throws  HttpException, IOException {
         return  sendRequest(url,  "UTF-8" , HttpMethod.POST, contentType);
     }
 
     /**
      * 根据url编码,请求方式,请求URL
     
      * @param urlstr
      * @param urlEncoding
      * @param bodyType
      * @return
      * @throws HttpException
      * @throws IOException
      */
     public  ResponseStatus sendRequest(String urlstr, String urlEncoding, HttpMethod bodyType, String contentType)
             throws  HttpException, IOException {
 
         if  (urlstr ==  null )
             return  null ;
 
         String url = urlstr;
         if  (urlEncoding !=  null )
             url = HttpClientWrapper.encodeURL(url.trim(), urlEncoding);
         
         HttpEntity entity =  null ;
         HttpRequestBase request =  null ;
         CloseableHttpResponse response =  null ;
         try  {
             if  (HttpMethod.GET == bodyType) {
                 request =  new  HttpGet(url);
             else  if  (HttpMethod.POST == bodyType) {
                 this .parseUrl(url);
                 HttpPost httpPost =  new  HttpPost(toUrl());
                 List<NameValuePair> nvBodyList =  this .getNVBodies();
                 httpPost.setEntity( new  UrlEncodedFormEntity(nvBodyList, urlEncoding));
                 request = httpPost;
             }
 
             if  (contentType !=  null ) {
                 request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
             }
             
             //setTimeOut(request, timeout);
             request.addHeader(HttpHeaders.USER_AGENT,
                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)" );
 
             response = client.execute(request);
             entity = response.getEntity();  // 获取响应实体
             StatusLine statusLine = response.getStatusLine();
             ResponseStatus ret =  new  ResponseStatus();
             ret.setStatusCode(statusLine.getStatusCode());
             ret.setEncoding(urlEncoding);
             getResponseStatus(entity, ret);
             return  ret;
         finally  {
             close(entity, request, response);
         }
     }
     
     private  void  getResponseStatus(HttpEntity entity, ResponseStatus ret)  throws  IOException {
         Header enHeader = entity.getContentEncoding();
         if  (enHeader !=  null ) {
             String charset = enHeader.getValue().toLowerCase();
             ret.setEncoding(charset);
         }
         String contenttype =  this .getResponseStatusType(entity);
         ret.setContentType(contenttype);
         ret.setContentTypeString( this .getResponseStatusTypeString(entity));
         ret.setContentBytes(EntityUtils.toByteArray(entity));
     }
 
     public  ResponseStatus postEntity(String url)  throws  HttpException, IOException {
         return  this .postEntity(url,  "UTF-8" );
     }
 
     /**
      * POST方式发送名值对请求URL,上传文件(包括图片)
     
      * @param url
      * @return
      * @throws HttpException
      * @throws IOException
      */
     public  ResponseStatus postEntity(String url, String urlEncoding)  throws  HttpException, IOException {
         if  (url ==  null )
             return  null ;
 
         HttpEntity entity =  null ;
         HttpRequestBase request =  null ;
         CloseableHttpResponse response =  null ;
         try  {
             this .parseUrl(url);
             HttpPost httpPost =  new  HttpPost(toUrl());
 
             //对请求的表单域进行填充  
             MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
             entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
             for  (NameValuePair nameValuePair :  this .getNVBodies()) {
                 entityBuilder.addPart(nameValuePair.getName(),
                         new  StringBody(nameValuePair.getValue(), ContentType.create( "text/plain" , urlEncoding)));
             }
             for  (ContentBody contentBody : getContentBodies()) {
                 entityBuilder.addPart( "file" , contentBody);
             }
             entityBuilder.setCharset(CharsetUtils.get(urlEncoding));
             httpPost.setEntity(entityBuilder.build());
             request = httpPost;
             response = client.execute(request);
 
             //响应状态
             StatusLine statusLine = response.getStatusLine();
             // 获取响应对象
             entity = response.getEntity();
             ResponseStatus ret =  new  ResponseStatus();
             ret.setStatusCode(statusLine.getStatusCode());
             getResponseStatus(entity, ret);
             return  ret;
         finally  {
             close(entity, request, response);
         }
     }
 
     private  void  close(HttpEntity entity, HttpRequestBase request, CloseableHttpResponse response)  throws  IOException {
         if  (request !=  null )
             request.releaseConnection();
         if  (entity !=  null )
             entity.getContent().close();
         if  (response !=  null )
             response.close();
     }
 
     public  NameValuePair[] getNVBodyArray() {
         List<NameValuePair> list =  this .getNVBodies();
         if  (list ==  null  || list.isEmpty())
             return  null ;
         NameValuePair[] nvps =  new  NameValuePair[list.size()];
         Iterator<NameValuePair> it = list.iterator();
         int  count =  0 ;
         while  (it.hasNext()) {
             NameValuePair nvp = it.next();
             nvps[count++] = nvp;
         }
         return  nvps;
     }
 
     public  List<NameValuePair> getNVBodies() {
         return  Collections.unmodifiableList( this .nameValuePostBodies);
     }
 
     private  String getResponseStatusType(HttpEntity method) {
         Header contenttype = method.getContentType();
         if  (contenttype ==  null )
             return  null ;
         String ret =  null ;
         try  {
             HeaderElement[] hes = contenttype.getElements();
             if  (hes !=  null  && hes.length >  0 ) {
                 ret = hes[ 0 ].getName();
             }
         catch  (Exception e) {
         }
         return  ret;
     }
 
     private  String getResponseStatusTypeString(HttpEntity method) {
         Header contenttype = method.getContentType();
         if  (contenttype ==  null )
             return  null ;
         return  contenttype.getValue();
     }
 
     static  Set<Character> BEING_ESCAPED_CHARS =  new  HashSet<Character>();
     static  {
         char [] signArray = {  ' ' '\\' '‘' ']' '!' '^' '#' '`' '$' '{' '%' '|' '}' '(' '+' ')' '<' '>' ,
                 ';' '['  };
         for  ( int  i =  0 ; i < signArray.length; i++) {
             BEING_ESCAPED_CHARS.add( new  Character(signArray[i]));
         }
     }
 
     public  static  String encodeURL(String url, String encoding) {
         if  (url ==  null )
             return  null ;
         if  (encoding ==  null )
             return  url;
 
         StringBuffer sb =  new  StringBuffer();
         for  ( int  i =  0 ; i < url.length(); i++) {
             char  c = url.charAt(i);
             if  (c ==  10 ) {
                 continue ;
             else  if  (BEING_ESCAPED_CHARS.contains( new  Character(c)) || c ==  13  || c >  126 ) {
                 try  {
                     sb.append(URLEncoder.encode(String.valueOf(c), encoding));
                 catch  (Exception e) {
                     sb.append(c);
                 }
             else  {
                 sb.append(c);
             }
         }
         return  sb.toString().replaceAll( "\\+" "%20" );
     }
 
     private  String protocol;
     private  String host;
     private  int  port;
     private  String dir;
     private  String uri;
     private  final  static  int  DefaultPort =  80 ;
     private  final  static  String ProtocolSeparator =  "://" ;
     private  final  static  String PortSeparator =  ":" ;
     private  final  static  String HostSeparator =  "/" ;
     private  final  static  String DirSeparator =  "/" ;
 
     private  void  parseUrl(String url) {
         this .protocol =  null ;
         this .host =  null ;
         this .port = DefaultPort;
         this .dir =  "/" ;
         this .uri = dir;
 
         if  (url ==  null  || url.length() ==  0 )
             return ;
         String u = url.trim();
         boolean  MeetProtocol =  false ;
         int  pos = u.indexOf(ProtocolSeparator);
         if  (pos >  0 ) {
             MeetProtocol =  true ;
             this .protocol = u.substring( 0 , pos);
             pos += ProtocolSeparator.length();
         }
         int  posStartDir =  0 ;
         if  (MeetProtocol) {
             int  pos2 = u.indexOf(PortSeparator, pos);
             if  (pos2 >  0 ) {
                 this .host = u.substring(pos, pos2);
                 pos2 = pos2 + PortSeparator.length();
                 int  pos3 = u.indexOf(HostSeparator, pos2);
                 String PortStr =  null ;
                 if  (pos3 >  0 ) {
                     PortStr = u.substring(pos2, pos3);
                     posStartDir = pos3;
                 else  {
                     int  pos4 = u.indexOf( "?" );
                     if  (pos4 >  0 ) {
                         PortStr = u.substring(pos2, pos4);
                         posStartDir = - 1 ;
                     else  {
                         PortStr = u.substring(pos2);
                         posStartDir = - 1 ;
                     }
                 }
                 try  {
                     this .port = Integer.parseInt(PortStr);
                 catch  (Exception e) {
                 }
             else  {
                 pos2 = u.indexOf(HostSeparator, pos);
                 if  (pos2 >  0 ) {
                     this .host = u.substring(pos, pos2);
                     posStartDir = pos2;
                 else  {
                     this .host = u.substring(pos);
                     posStartDir = - 1 ;
                 }
             }
 
             pos = u.indexOf(HostSeparator, pos);
             pos2 = u.indexOf( "?" );
             if  (pos >  0  && pos2 >  0 ) {
                 this .uri = u.substring(pos, pos2);
             else  if  (pos >  0  && pos2 <  0 ) {
                 this .uri = u.substring(pos);
             }
         }
 
         if  (posStartDir >=  0 ) {
             int  pos2 = u.lastIndexOf(DirSeparator, posStartDir);
             if  (pos2 >  0 ) {
                 this .dir = u.substring(posStartDir, pos2 +  1 );
             }
         }
 
     }
 
     private  String toUrl() {
         StringBuffer ret =  new  StringBuffer();
         if  ( this .protocol !=  null ) {
             ret.append( this .protocol);
             ret.append(ProtocolSeparator);
             if  ( this .host !=  null )
                 ret.append( this .host);
             if  ( this .port != DefaultPort) {
                 ret.append(PortSeparator);
                 ret.append( this .port);
             }
         }
         ret.append( this .uri);
         return  ret.toString();
     }
 
     public  void  addNV(String name, String value) {
         BasicNameValuePair nvp =  new  BasicNameValuePair(name, value);
         this .nameValuePostBodies.add(nvp);
     }
 
     public  void  clearNVBodies() {
         this .nameValuePostBodies.clear();
     }
 
     public  List<ContentBody> getContentBodies() {
         return  contentBodies;
     }
 
}
?
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
package  com.httpclint.util;
 
public  class  HttpProxy {
 
     private  String host;
     private  int  port;
     private  String user;
     private  String password;
 
     public  HttpProxy(String ipAndPort) {
         this .host = ipAndPort.split( ":" )[ 0 ];
         this .port = Integer.parseInt(ipAndPort.split( ":" )[ 1 ]);
     }
 
     public  HttpProxy(String host,  int  port) {
         super ();
         this .host = host;
         this .port = port;
     }
 
     public  HttpProxy(String host,  int  port, String user, String password) {
         super ();
         this .host = host;
         this .port = port;
         this .user = user;
         this .password = password;
     }
 
     public  String getHost() {
         return  host;
     }
 
     public  void  setHost(String host) {
         this .host = host;
     }
 
     public  int  getPort() {
         return  port;
     }
 
     public  void  setPort( int  port) {
         this .port = port;
     }
 
     public  String getUser() {
         return  user;
     }
 
     public  void  setUser(String user) {
         this .user = user;
     }
 
     public  String getPassword() {
         return  password;
     }
 
     public  void  setPassword(String password) {
         this .password = password;
     }
 
}
?
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
package  com.httpclint.util;
  
import  java.io.UnsupportedEncodingException;
  
/**
  * 封装HttpClient返回数据
  * <p>
  * @author   yangjian1004
  * @Date     Aug 5, 2014     
  */
public  class  ResponseStatus {
     
     private  String encoding;
  
     private  byte [] contentBytes;
  
     private  int  statusCode;
  
     private  String contentType;
  
     private  String contentTypeString;
  
     public  String getEncoding() {
         return  encoding;
     }
  
     public  void  setEncoding(String encoding) {
         this .encoding = encoding;
     }
  
     public  String getContentType() {
         return  this .contentType;
     }
  
     public  void  setContentType(String contentType) {
         this .contentType = contentType;
     }
  
     public  String getContentTypeString() {
         return  this .contentTypeString;
     }
  
     public  void  setContentTypeString(String contenttypeString) {
         this .contentTypeString = contenttypeString;
     }
  
     public  String getContent()  throws  UnsupportedEncodingException {
         return  this .getContent( this .encoding);
     }
  
     public  String getContent(String encoding)  throws  UnsupportedEncodingException {
         if  (encoding ==  null ) {
             return  new  String(contentBytes);
         }
         return  new  String(contentBytes, encoding);
     }
  
     public  String getUTFContent()  throws  UnsupportedEncodingException {
         return  this .getContent( "UTF-8" );
     }
  
     public  byte [] getContentBytes() {
         return  contentBytes;
     }
  
     public  void  setContentBytes( byte [] contentBytes) {
         this .contentBytes = contentBytes;
     }
  
     public  int  getStatusCode() {
         return  statusCode;
     }
  
     public  void  setStatusCode( int  statusCode) {
         this .statusCode = statusCode;
     }
  
}

http://download.csdn.net/detail/jelly_8090/7923537

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值