Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.qiniu.android.http;
  
  
  import  org.apache.http.Header;
  import  org.apache.http.HttpEntity;
 import  org.apache.http.message.BasicHeader;
 import  org.json.JSONObject;
 
 import java.net.URI;
 import java.util.Map;
 
 import static java.lang.String.format;

定义HTTP请求管理相关方法
 
 public final class HttpManager {
     private static final String userAgent = getUserAgent();
     private AsyncHttpClient client;
     private IReport reporter;
     private String backUpIp;
     private UrlConverter converter;
 
     public HttpManager(Proxy proxy) {
         this(proxynull);
     }
 
     public HttpManager(Proxy proxyIReport reporter) {
         this(proxyreporternull, 10, 30, null);
     }
 
     public HttpManager(Proxy proxyIReport reporterString backUpIp,
                        int connectTimeoutint responseTimeoutUrlConverter converter) {
         this. = backUpIp;
          = new AsyncHttpClient();
         .setConnectTimeout(connectTimeout*1000);
         .setResponseTimeout(responseTimeout * 1000);
         .setUserAgent();
         .setEnableRedirects(true);
         .setRedirectHandler(new UpRedirectHandler());
         AsyncHttpClient.blockRetryExceptionClass(CancellationHandler.CancellationException.class);
         if (proxy != null) {
             .setProxy(proxy.hostAddressproxy.portproxy.userproxy.password);
         }
         this. = reporter;
         if (reporter == null) {
             this. = new IReport() {
                 @Override
                 public Header[] appendStatHeaders(Header[] headers) {
                     return headers;
                 }
 
                 @Override
                 public void updateErrorInfo(ResponseInfo info) {
 
                 }
 
                 @Override
                 public void updateSpeedInfo(ResponseInfo info) {
 
                 }
             };
         }
 
         this. = converter;
     }
 
     public HttpManager() {
         this(null);
     }
 
     private static String genId() {
         Random r = new Random();
         return System.currentTimeMillis() + "" + r.nextInt(999);
     }
 
     private static String getUserAgent() {
         return format("QiniuAndroid/%s (%s; %s; %s)".,
                 android.os.Build.VERSION.RELEASE, android.os.Build.MODEL, genId());
     }

    
以POST方法发送请求数据

Parameters:
url 请求的URL
data 发送的数据
offset 发送的数据起始字节索引
size 发送的数据字节长度
headers 发送的数据请求头部
progressHandler 发送数据进度处理对象
completionHandler 发送数据完成后续动作处理对象
    public void postData(String urlbyte[] dataint offsetint size, Header[] headers,
                         ProgressHandler progressHandlerfinal CompletionHandler completionHandlerCancellationHandler cboolean forceIp) {
        ByteArrayEntity entity = new ByteArrayEntity(dataoffsetsizeprogressHandlerc);
        postEntity(urlentityheadersprogressHandlercompletionHandlerforceIp);
    }
    public void postData(String urlbyte[] data, Header[] headersProgressHandler progressHandler,
                         CompletionHandler completionHandlerCancellationHandler cboolean forceIp) {
        postData(urldata, 0, data.lengthheadersprogressHandlercompletionHandlercforceIp);
    }
    private void postEntity(String urlfinal HttpEntity entity, Header[] headers,
                         final ProgressHandler progressHandlerfinal CompletionHandler completionHandlerfinal boolean forceIp) {
        final CompletionHandler wrapper = wrap(completionHandler);
        final Header[] h = .appendStatHeaders(headers);
        if ( != null){
            url = .convert(url);
        }
        ResponseHandler handler = new ResponseHandler(urlwrapperprogressHandler);
        if( == null ||  != null){
            .post(nullurlhentitynullhandler);
            return;
        }
        final String url2 = url;
        ExecutorService t = .getThreadPool();
        t.execute(new Runnable() {
            @Override
            public void run() {
                final URI uri = URI.create(url2);
                String ip = null;
                if (forceIp) {
                    ip = ;
                }else {
                    ip = Dns.getAddress(uri.getHost());
                    if (ip == null || ip.equals("")){
                        ip = ;
                    }
                }
                final Header[] h2 = new Header[h.length + 1];
                System.arraycopy(h, 0, h2, 0, h.length);
                String newUrl = null;
                try {
                    newUrl = new URI(uri.getScheme(), nullipuri.getPort(), uri.getPath(), uri.getQuery(), null).toString();
                } catch (URISyntaxException e) {
                    throw new AssertionError(e);
                }
                h2[h.length] = new BasicHeader("Host"uri.getHost());
                final String ip2 = ip;
                ResponseHandler handler2 = new ResponseHandler(url2wrap(new CompletionHandler() {
                    @Override
                    public void complete(ResponseInfo info, JSONObject response) {
                        if (uri.getPort() == 80 || info.statusCode != .){
                            completionHandler.complete(inforesponse);
                            return;
                        }
                        String newUrl80 = null;
                        try {
                            newUrl80 = new URI(uri.getScheme(), nullip2, 80, uri.getPath(), uri.getQuery(), null).toString();
                        } catch (URISyntaxException e) {
                            throw new AssertionError(e);
                        }
                        ResponseHandler handler3 = new ResponseHandler(newUrl80completionHandlerprogressHandler);
                        .post(nullnewUrl80h2entitynullhandler3);
                    }
                }), progressHandler);
                .post(nullnewUrlh2entitynullhandler2);
            }
        });
    }

    
以POST方式发送multipart/form-data格式数据

Parameters:
url 请求的URL
args 发送的数据
progressHandler 发送数据进度处理对象
completionHandler 发送数据完成后续动作处理对象
    public void multipartPost(String urlPostArgs argsProgressHandler progressHandler,
                              final CompletionHandler completionHandlerCancellationHandler cboolean forceIp) {
        MultipartBuilder mbuilder = new MultipartBuilder();
        for (Map.Entry<StringStringentry : args.params.entrySet()) {
            mbuilder.addPart(entry.getKey(), entry.getValue());
        }
        if (args.data != null) {
            ByteArrayInputStream buff = new ByteArrayInputStream(args.data);
            try {
                mbuilder.addPart("file"args.fileNamebuffargs.mimeType);
            } catch (IOException e) {
                completionHandler.complete(ResponseInfo.fileError(e), null);
                return;
            }
        } else {
            try {
                mbuilder.addPart("file"args.fileargs.mimeType"filename");
            } catch (IOException e) {
                completionHandler.complete(ResponseInfo.fileError(e), null);
                return;
            }
        }
        ByteArrayEntity entity = mbuilder.build(progressHandlerc);
        Header[] h = .appendStatHeaders(new Header[0]);
        postEntity(urlentityhprogressHandlercompletionHandlerforceIp);
    }
    private CompletionHandler wrap(final CompletionHandler completionHandler) {
        return new CompletionHandler() {
            @Override
            public void complete(ResponseInfo info, JSONObject response) {
                completionHandler.complete(inforesponse);
                if (info.isOK()) {
                    .updateSpeedInfo(info);
                } else {
                    .updateErrorInfo(info);
                }
            }
        };
    }
New to GrepCode? Check out our FAQ X