zoukankan      html  css  js  c++  java
  • 网络数据的获取(获取JSON数据s)

    转载某处。。。。

    使用前需要导入包gson-2.2.4.jar。下载链接:http://pan.baidu.com/s/1jGonkY6

    说明:共4步,前3步为包和所需要的文件,第4步为一个小例子。

    1、客户端异步请求

        AsyncHttpClient可以用来异步加载GET、POST和DELETE HTTP请求在你的android应用中。 这些请求可以和通过其他参数的实例(如 RequestParams){@link RequestParams},或者响 应可以通过一个匿名覆盖的处理实例(如 AsyncHttpResponseHandler) {@link AsyncHttpResponseHandler}实现。源码如下:

    import java.io.IOException;
    import java.io.InputStream;
    import java.lang.ref.WeakReference;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.WeakHashMap;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.zip.GZIPInputStream;
    
    import org.apache.http.Header;
    import org.apache.http.HeaderElement;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpRequest;
    import org.apache.http.HttpRequestInterceptor;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpResponseInterceptor;
    import org.apache.http.HttpVersion;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpDelete;
    import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.client.protocol.ClientContext;
    import org.apache.http.conn.params.ConnManagerParams;
    import org.apache.http.conn.params.ConnPerRouteBean;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.entity.HttpEntityWrapper;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpProtocolParams;
    import org.apache.http.protocol.BasicHttpContext;
    import org.apache.http.protocol.HttpContext;
    import org.apache.http.protocol.SyncBasicHttpContext;
    
    import android.content.Context;
    
    
    /**
     * 客户端异步请求
     *
     * The AsyncHttpClient can be used to make asynchronous GET, POST, PUT and
     * DELETE HTTP requests in your Android applications. Requests can be made
     * with additional parameters by passing a {@link RequestParams} instance,
     * and responses can be handled by passing an anonymously overridden
     * {@link AsyncHttpResponseHandler} instance.
     * AsyncHttpClient可以用来异步加载GET、POST和DELETE HTTP请求在你的android应用中。
     * 这些请求可以和通过其他参数的实例(如 RequestParams){@link RequestParams},或者响
     * 应可以通过一个匿名覆盖的处理实例(如 AsyncHttpResponseHandler)
     * {@link AsyncHttpResponseHandler}实现
     * <p/>
     * <p/>
     * For example:
     * <p/>
     * <pre>
     * AsyncHttpClient client = new AsyncHttpClient();
     * client.get("http://www.google.com", new AsyncHttpResponseHandler() {
     *     &#064;Override
     *     public void onSuccess(String response) {
     *         System.out.println(response);
     *     }
     * });
     * </pre>
     */
    public class AsyncHttpClient {
        private static final String VERSION = "1.3.1";
    
        private static final int DEFAULT_MAX_CONNECTIONS = 10;
        private static final int DEFAULT_SOCKET_TIMEOUT = 10 * 1000;
        private static final int DEFAULT_MAX_RETRIES = 5;
        private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
        private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
        private static final String ENCODING_GZIP = "gzip";
    
        private static int maxConnections = DEFAULT_MAX_CONNECTIONS;
        private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
    
        private final DefaultHttpClient httpClient;
        private final HttpContext httpContext;
        private ThreadPoolExecutor threadPool;//线程池
        private final Map<Context, List<WeakReference<Future<?>>>> requestMap;
        private final Map<String, String> clientHeaderMap;
    
    
        /**
         * Creates a new AsyncHttpClient.
         */
        public AsyncHttpClient() {
            BasicHttpParams httpParams = new BasicHttpParams();
    
            ConnManagerParams.setTimeout(httpParams, socketTimeout);
            ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
            ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    
            HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
            HttpConnectionParams.setTcpNoDelay(httpParams, true);
            HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);
    
            HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    
            httpContext = new SyncBasicHttpContext(new BasicHttpContext());
            httpClient = new DefaultHttpClient(cm, httpParams);
            httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                public void process(HttpRequest request, HttpContext context) {
                    if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                        request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
                    }
                    for (String header : clientHeaderMap.keySet()) {
                        request.addHeader(header, clientHeaderMap.get(header));
                    }
                }
            });
    
            httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
                public void process(HttpResponse response, HttpContext context) {
                    final HttpEntity entity = response.getEntity();
                    final Header encoding = entity.getContentEncoding();
                    if (encoding != null) {
                        for (HeaderElement element : encoding.getElements()) {
                            if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                                response.setEntity(new InflatingEntity(response.getEntity()));
                                break;
                            }
                        }
                    }
                }
            });
    
            httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));
    
            threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    
            requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
            clientHeaderMap = new HashMap<String, String>();
        }
    
        /**
         * Get the underlying HttpClient instance. This is useful for setting
         * additional fine-grained settings for requests by accessing the
         * client's ConnectionManager, HttpParams and SchemeRegistry.
         */
        public HttpClient getHttpClient() {
            return this.httpClient;
        }
    
        /**
         * Sets an optional CookieStore to use when making requests
         *
         * @param cookieStore The CookieStore implementation to use, usually an instance of {@link PersistentCookieStore}
         */
        public void setCookieStore(CookieStore cookieStore) {
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        }
    
        /**
         * Overrides the threadpool implementation used when queuing/pooling
         * requests. By default, Executors.newCachedThreadPool() is used.
         *
         * @param threadPool an instance of {@link ThreadPoolExecutor} to use for queuing/pooling requests.
         */
        public void setThreadPool(ThreadPoolExecutor threadPool) {
            this.threadPool = threadPool;
        }
    
        /**
         * Sets the User-Agent header to be sent with each request. By default,
         * "Android Asynchronous Http Client/VERSION (http://loopj.com/android-async-http/)" is used.
         *
         * @param userAgent the string to use in the User-Agent header.
         */
        public void setUserAgent(String userAgent) {
            HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
        }
    
        /**
         * Sets the SSLSocketFactory to user when making requests. By default,
         * a new, default SSLSocketFactory is used.
         *
         * @param sslSocketFactory the socket factory to use for https requests.
         */
        public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
            this.httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sslSocketFactory, 443));
        }
    
        /**
         * Sets headers that will be added to all requests this client makes (before sending).
         *
         * @param header the name of the header
         * @param value  the contents of the header
         */
        public void addHeader(String header, String value) {
            clientHeaderMap.put(header, value);
        }
    
        /**
         * Cancels any pending (or potentially active) requests associated with the
         * passed Context.
         * <p/>
         * <b>Note:</b> This will only affect requests which were created with a non-null
         * android Context. This method is intended to be used in the onDestroy
         * method of your android activities to destroy all requests which are no
         * longer required.
         *
         * @param context               the android Context instance associated to the request.
         * @param mayInterruptIfRunning specifies if active requests should be cancelled along with pending requests.
         */
        public void cancelRequests(Context context, boolean mayInterruptIfRunning) {
            List<WeakReference<Future<?>>> requestList = requestMap.get(context);
            if (requestList != null) {
                for (WeakReference<Future<?>> requestRef : requestList) {
                    Future<?> request = requestRef.get();
                    if (request != null) {
                        request.cancel(mayInterruptIfRunning);
                    }
                }
            }
            requestMap.remove(context);
        }
    
    
        //
        // HTTP GET Requests
        //
    
        /**
         * Perform a HTTP GET request, without any parameters.
         *
         * @param url             the URL to send the request to.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void get(String url, AsyncHttpResponseHandler responseHandler) {
            get(null, url, null, responseHandler);
        }
    
        /**
         * Perform a HTTP GET request with parameters.
         *
         * @param url             the URL to send the request to.
         * @param params          additional GET parameters to send with the request.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
            get(null, url, params, responseHandler);
        }
    
        /**
         * Perform a HTTP GET request without any parameters and track the Android Context which initiated the request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void get(Context context, String url, AsyncHttpResponseHandler responseHandler) {
            get(context, url, null, responseHandler);
        }
    
        /**
         * Perform a HTTP GET request and track the Android Context which initiated the request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param params          additional GET parameters to send with the request.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void get(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
            sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null, responseHandler, context);
        }
    
    
        //
        // HTTP POST Requests
        //
    
        /**
         * Perform a HTTP POST request, without any parameters.
         *
         * @param url             the URL to send the request to.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void post(String url, AsyncHttpResponseHandler responseHandler) {
            post(null, url, null, responseHandler);
        }
    
        /**
         * Perform a HTTP POST request with parameters.
         *
         * @param url             the URL to send the request to.
         * @param params          additional POST parameters or files to send with the request.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
            post(null, url, params, responseHandler);
        }
    
        /**
         * Perform a HTTP POST request and track the Android Context which initiated the request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param params          additional POST parameters or files to send with the request.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void post(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
            post(context, url, paramsToEntity(params), null, responseHandler);
        }
    
        /**
         * Perform a HTTP POST request and track the Android Context which initiated the request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param entity          a raw {@link HttpEntity} to send with the request, for example, use this to send string/json/xml payloads to a server by passing a {@link org.apache.http.entity.StringEntity}.
         * @param contentType     the content type of the payload you are sending, for example application/json if sending a json payload.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
            sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPost(url), entity), contentType, responseHandler, context);
        }
    
    
        //
        // HTTP PUT Requests
        //
    
        /**
         * Perform a HTTP PUT request, without any parameters.
         *
         * @param url             the URL to send the request to.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void put(String url, AsyncHttpResponseHandler responseHandler) {
            put(null, url, null, responseHandler);
        }
    
        /**
         * Perform a HTTP PUT request with parameters.
         *
         * @param url             the URL to send the request to.
         * @param params          additional PUT parameters or files to send with the request.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void put(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
            put(null, url, params, responseHandler);
        }
    
        /**
         * Perform a HTTP PUT request and track the Android Context which initiated the request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param params          additional PUT parameters or files to send with the request.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void put(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
            put(context, url, paramsToEntity(params), null, responseHandler);
        }
    
        /**
         * Perform a HTTP PUT request and track the Android Context which initiated the request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param entity          a raw {@link HttpEntity} to send with the request, for example, use this to send string/json/xml payloads to a server by passing a {@link org.apache.http.entity.StringEntity}.
         * @param contentType     the content type of the payload you are sending, for example application/json if sending a json payload.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void put(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
            sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPut(url), entity), contentType, responseHandler, context);
        }
    
    
        //
        // HTTP DELETE Requests
        //
    
        /**
         * Perform a HTTP DELETE request.
         *
         * @param url             the URL to send the request to.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void delete(String url, AsyncHttpResponseHandler responseHandler) {
            delete(null, url, responseHandler);
        }
    
        /**
         * Perform a HTTP DELETE request.
         *
         * @param context         the Android Context which initiated the request.
         * @param url             the URL to send the request to.
         * @param responseHandler the response handler instance that should handle the response.
         */
        public void delete(Context context, String url, AsyncHttpResponseHandler responseHandler) {
            final HttpDelete delete = new HttpDelete(url);
            sendRequest(httpClient, httpContext, delete, null, responseHandler, context);
        }
    
    
        // Private stuff
        private void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
            if (contentType != null) {
                uriRequest.addHeader("Content-Type", contentType);
            }
    
            Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));
    
            if (context != null) {
                // Add request to request map
                List<WeakReference<Future<?>>> requestList = requestMap.get(context);
                if (requestList == null) {
                    requestList = new LinkedList<WeakReference<Future<?>>>();
                    requestMap.put(context, requestList);
                }
    
                requestList.add(new WeakReference<Future<?>>(request));
    
                // TODO: Remove dead weakrefs from requestLists?
            }
        }
    
        private String getUrlWithQueryString(String url, RequestParams params) {
            if (params != null) {
                String paramString = params.getParamString();
                url += "?" + paramString;
            }
    
            return url;
        }
    
        private HttpEntity paramsToEntity(RequestParams params) {
            HttpEntity entity = null;
    
            if (params != null) {
                entity = params.getEntity();
            }
    
            return entity;
        }
    
        private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
            if (entity != null) {
                requestBase.setEntity(entity);
            }
    
            return requestBase;
        }
    
        private static class InflatingEntity extends HttpEntityWrapper {
            public InflatingEntity(HttpEntity wrapped) {
                super(wrapped);
            }
    
            @Override
            public InputStream getContent() throws IOException {
                return new GZIPInputStream(wrappedEntity.getContent());
            }
    
            @Override
            public long getContentLength() {
                return -1;
            }
        }
    }

    2、AsyncHttpResponseHandler文件,见下源码:

    import java.io.IOException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.StatusLine;
    import org.apache.http.client.HttpResponseException;
    import org.apache.http.entity.BufferedHttpEntity;
    import org.apache.http.util.EntityUtils;
    
    import android.os.Handler;
    import android.os.Looper;
    import android.os.Message;
    
    /**
     * Used to intercept and handle the responses from requests made using 
     * {@link AsyncHttpClient}. The {@link #onSuccess(String)} method is 
     * designed to be anonymously overridden with your own response handling code.
     * <p>
     * Additionally, you can override the {@link #onFailure(Throwable, String)},
     * {@link #onStart()}, and {@link #onFinish()} methods as required.
     * <p>
     * For example:
     * <p>
     * <pre>
     * AsyncHttpClient client = new AsyncHttpClient();
     * client.get("http://www.google.com", new AsyncHttpResponseHandler() {
     *     &#064;Override
     *     public void onStart() {
     *         // Initiated the request
     *     }
     *
     *     &#064;Override
     *     public void onSuccess(String response) {
     *         // Successfully got a response
     *     }
     * 
     *     &#064;Override
     *     public void onFailure(Throwable e, String response) {
     *         // Response failed :(
     *     }
     *
     *     &#064;Override
     *     public void onFinish() {
     *         // Completed the request (either success or failure)
     *     }
     * });
     * </pre>
     */
    public class AsyncHttpResponseHandler {
        private static final int SUCCESS_MESSAGE = 0;
        private static final int FAILURE_MESSAGE = 1;
        private static final int START_MESSAGE = 2;
        private static final int FINISH_MESSAGE = 3;
    
        private Handler handler;
    
        /**
         * Creates a new AsyncHttpResponseHandler
         */
        public AsyncHttpResponseHandler() {
            // Set up a handler to post events back to the correct thread if possible
            if(Looper.myLooper() != null) {
                handler = new Handler(){
                    public void handleMessage(Message msg){
                        AsyncHttpResponseHandler.this.handleMessage(msg);
                    }
                };
            }
        }
    
    
        //
        // Callbacks to be overridden, typically anonymously
        //
    
        /**
         * Fired when the request is started, override to handle in your own code
         */
        public void onStart() {}
    
        /**
         * Fired in all cases when the request is finished, after both success and failure, override to handle in your own code
         */
        public void onFinish() {}
    
        /**
         * Fired when a request returns successfully, override to handle in your own code
         * @param content the body of the HTTP response from the server
         */
        public void onSuccess(String content) {}
    
        /**
         * Fired when a request fails to complete, override to handle in your own code
         * @param error the underlying cause of the failure
         * @deprecated use {@link #onFailure(Throwable, String)}
         */
        public void onFailure(Throwable error) {}
    
        /**
         * Fired when a request fails to complete, override to handle in your own code
         * @param error the underlying cause of the failure
         * @param content the response body, if any
         */
        public void onFailure(Throwable error, String content) {
            // By default, call the deprecated onFailure(Throwable) for compatibility
            onFailure(error);
        }
    
    
        //
        // Pre-processing of messages (executes in background threadpool thread)
        //
    
        protected void sendSuccessMessage(String responseBody) {
            sendMessage(obtainMessage(SUCCESS_MESSAGE, responseBody));
        }
    
        protected void sendFailureMessage(Throwable e, String responseBody) {
            sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{e, responseBody}));
        }
    
        protected void sendStartMessage() {
            sendMessage(obtainMessage(START_MESSAGE, null));
        }
    
        protected void sendFinishMessage() {
            sendMessage(obtainMessage(FINISH_MESSAGE, null));
        }
    
    
        //
        // Pre-processing of messages (in original calling thread, typically the UI thread)
        //
    
        protected void handleSuccessMessage(String responseBody) {
            onSuccess(responseBody);
        }
    
        protected void handleFailureMessage(Throwable e, String responseBody) {
            onFailure(e, responseBody);
        }
    
    
    
        // Methods which emulate android's Handler and Message methods
        protected void handleMessage(Message msg) {
            switch(msg.what) {
                case SUCCESS_MESSAGE:
                    handleSuccessMessage((String)msg.obj);
                    break;
                case FAILURE_MESSAGE:
                    Object[] repsonse = (Object[])msg.obj;
                    handleFailureMessage((Throwable)repsonse[0], (String)repsonse[1]);
                    break;
                case START_MESSAGE:
                    onStart();
                    break;
                case FINISH_MESSAGE:
                    onFinish();
                    break;
            }
        }
    
        protected void sendMessage(Message msg) {
            if(handler != null){
                handler.sendMessage(msg);
            } else {
                handleMessage(msg);
            }
        }
    
        protected Message obtainMessage(int responseMessage, Object response) {
            Message msg = null;
            if(handler != null){
                msg = this.handler.obtainMessage(responseMessage, response);
            }else{
                msg = new Message();
                msg.what = responseMessage;
                msg.obj = response;
            }
            return msg;
        }
    
    
        // Interface to AsyncHttpRequest
        void sendResponseMessage(HttpResponse response) {
            StatusLine status = response.getStatusLine();
            String responseBody = null;
            try {
                HttpEntity entity = null;
                HttpEntity temp = response.getEntity();
                if(temp != null) {
                    entity = new BufferedHttpEntity(temp);
                }
                responseBody = EntityUtils.toString(entity,"UTF-8");
            } catch(IOException e) {
                sendFailureMessage(e, null);
            }
    
            if(status.getStatusCode() >= 300) {
                sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
            } else {
                sendSuccessMessage(responseBody);
            }
        }
    }

    3、RequestParams文件,见下源码:

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.message.BasicNameValuePair;
    
    /**
     * A collection of string request parameters or files to send along with
     * requests made from an {@link AsyncHttpClient} instance.
     * <p>
     * For example:
     * <p>
     * <pre>
     * RequestParams params = new RequestParams();
     * params.put("username", "james");
     * params.put("password", "123456");
     * params.put("email", "my&#064;email.com");
     * params.put("profile_picture", new File("pic.jpg")); // Upload a File
     * params.put("profile_picture2", someInputStream); // Upload an InputStream
     * params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
     *
     * AsyncHttpClient client = new AsyncHttpClient();
     * client.post("http://myendpoint.com", params, responseHandler);
     * </pre>
     */
    public class RequestParams {
        private static String ENCODING = "UTF-8";
    
        protected ConcurrentHashMap<String, String> urlParams;
        protected ConcurrentHashMap<String, FileWrapper> fileParams;
    
        /**
         * Constructs a new empty <code>RequestParams</code> instance.
         */
        public RequestParams() {
            init();
        }
    
        /**
         * Constructs a new RequestParams instance containing the key/value
         * string params from the specified map.
         * @param source the source key/value string map to add.
         */
        public RequestParams(Map<String, String> source) {
            init();
    
            for(Map.Entry<String, String> entry : source.entrySet()) {
                put(entry.getKey(), entry.getValue());
            }
        }
    
        /**
         * Constructs a new RequestParams instance and populate it with a single
         * initial key/value string param.
         * @param key the key name for the intial param.
         * @param value the value string for the initial param.
         */
        public RequestParams(String key, String value) {
            init();
    
            put(key, value);
        }
    
        /**
         * Adds a key/value string pair to the request.
         * @param key the key name for the new param.
         * @param value the value string for the new param.
         */
        public void put(String key, String value){
            if(key != null && value != null) {
                urlParams.put(key, value);
            }
        }
    
        /**
         * Adds a file to the request.
         * @param key the key name for the new param.
         * @param file the file to add.
         */
        public void put(String key, File file) throws FileNotFoundException {
            put(key, new FileInputStream(file), file.getName());
        }
    
        /**
         * Adds an input stream to the request.
         * @param key the key name for the new param.
         * @param stream the input stream to add.
         */
        public void put(String key, InputStream stream) {
            put(key, stream, null);
        }
    
        /**
         * Adds an input stream to the request.
         * @param key the key name for the new param.
         * @param stream the input stream to add.
         * @param fileName the name of the file.
         */
        public void put(String key, InputStream stream, String fileName) {
            put(key, stream, fileName, null);
        }
    
        /**
         * Adds an input stream to the request.
         * @param key the key name for the new param.
         * @param stream the input stream to add.
         * @param fileName the name of the file.
         * @param contentType the content type of the file, eg. application/json
         */
        public void put(String key, InputStream stream, String fileName, String contentType) {
            if(key != null && stream != null) {
                fileParams.put(key, new FileWrapper(stream, fileName, contentType));
            }
        }
    
        /**
         * Removes a parameter from the request.
         * @param key the key name for the parameter to remove.
         */
        public void remove(String key){
            urlParams.remove(key);
            fileParams.remove(key);
        }
    
        @Override
        public String toString() {
            StringBuilder result = new StringBuilder();
            for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
                if(result.length() > 0)
                    result.append("&");
    
                result.append(entry.getKey());
                result.append("=");
                result.append(entry.getValue());
            }
    
            for(ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
                if(result.length() > 0)
                    result.append("&");
    
                result.append(entry.getKey());
                result.append("=");
                result.append("FILE");
            }
    
            return result.toString();
        }
    
        HttpEntity getEntity() {
            HttpEntity entity = null;
    
            if(!fileParams.isEmpty()) {
                SimpleMultipartEntity multipartEntity = new SimpleMultipartEntity();
    
                // Add string params
                for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
                    multipartEntity.addPart(entry.getKey(), entry.getValue());
                }
    
                // Add file params
                int currentIndex = 0;
                int lastIndex = fileParams.entrySet().size() - 1;
                for(ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
                    FileWrapper file = entry.getValue();
                    if(file.inputStream != null) {
                        boolean isLast = currentIndex == lastIndex;
                        if(file.contentType != null) {
                            multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast);
                        } else {
                            multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast);
                        }
                    }
                    currentIndex++;
                }
    
                entity = multipartEntity;
            } else {
                try {
                    entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
    
            return entity;
        }
    
        private void init(){
            urlParams = new ConcurrentHashMap<String, String>();
            fileParams = new ConcurrentHashMap<String, FileWrapper>();
        }
    
        protected List<BasicNameValuePair> getParamsList() {
            List<BasicNameValuePair> lparams = new LinkedList<BasicNameValuePair>();
    
            for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
                lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
    
            return lparams;
        }
    
        protected String getParamString() {
            return URLEncodedUtils.format(getParamsList(), ENCODING);
        }
    
        private static class FileWrapper {
            public InputStream inputStream;
            public String fileName;
            public String contentType;
    
            public FileWrapper(InputStream inputStream, String fileName, String contentType) {
                this.inputStream = inputStream;
                this.fileName = fileName;
                this.contentType = contentType;
            }
    
            public String getFileName() {
                if(fileName != null) {
                    return fileName;
                } else {
                    return "nofilename";
                }
            }
        }
    }

    4、一个例子的应用:

    private void loadData() {
            try {
                AsyncHttpClient client = new AsyncHttpClient(); //实例化AsyncHttpClient 对象
                JSONObject object = new JSONObject();
                object.put("userID", mUserID);
                object.put("pageIndex", pageIndex);
                object.put("pageSize", pagesize);
                object.put("ticket", mTicket); //需要的参数
                byte[] bytes = object.toString().getBytes("utf-8");
                ByteArrayEntity stringEntity = new ByteArrayEntity(bytes); //转化参数
                client.post(this, TASK_URL, stringEntity, "application/json", //调用AsyncHttpClient 的post方法
                        new AsyncHttpResponseHandler() { //新建一个AsyncHttpResponseHandler对象,并重写onStart、onSuccess、onFailure、onFinish方法
                            @Override
                            // 开始加载数据
                            public void onStart() {
                                layLoading.setVisibility(View.VISIBLE);
                            }
                            @Override
                            // 加载数据成功
                            public void onSuccess(String result) {
                                line.setVisibility(View.VISIBLE);
                                if (setList(result)) {
                                } else {
                                    alert("数据加载失败...");
                                }
                                onLoad();
                            }
                            @Override
                            // 加载数据失败
                            public void onFailure(Throwable error) {
                                // listView.setAdapter(null);
                                listView.setVisibility(View.INVISIBLE);
                                onLoad();
                                alert("网络不稳定、数据加载失败...");
                                // TODO 顶部现实网络问题�
                            }
                            @Override
                            public void onFinish() {
                                super.onFinish();
                                mListView.setVisibility(View.VISIBLE);
                            }
                        }
                );
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
  • 相关阅读:
    Codeforces Round #578 (Div. 2) 训练总结及题解
    docker
    使用java遍历Map集合的方式
    SpringCloud集成rabbitmq:org.springframework.amqp.AmqpConnectException: java.net.ConnectException的解决办法
    创建新Docker容器时出现“The container name "/xxx" is already in use by container xxxxxxxxxxx...”问题的解决办法
    springBoot 项目中,使用定时任务报错
    java获取当前日期和前一周、前一月、前一年的日期
    用户行为PV&UV
    使用IDEA开发,多模块依赖中,找不到依赖: 程序包xxx.xxx.xxx不存在的问题
    Java获取本地IP地址和主机名
  • 原文地址:https://www.cnblogs.com/ccddy/p/3965913.html
Copyright © 2011-2022 走看看