com.lurencun.cfuture09.androidkit.http.Http.java Source code

Java tutorial

Introduction

Here is the source code for com.lurencun.cfuture09.androidkit.http.Http.java

Source

/*
 * @(#)Http.java             Project:androidkit
 * Date:2013-4-21
 *
 * Copyright (c) 2013 CFuture09, Institute of Software, 
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lurencun.cfuture09.androidkit.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;

import com.githang.androidkit.utils.Log4AK;
import com.githang.androidkit.utils.io.IOUtils;
import com.lurencun.cfuture09.androidkit.utils.lang.IdGenerator;
import com.lurencun.cfuture09.androidkit.utils.lang.IncreaseIntId;
import com.lurencun.cfuture09.androidkit.utils.thread.HandlerFactory;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * ??HTTPGET,POST,PUT,DELETE
 * 
 * @author Geek_Soledad (66704238@51uc.com)
 */
public class Http {
    public static final Log4AK log = Log4AK.getLog(Http.class);
    private static final int ONE_KB = 1024;
    private static final int BUFFER_SIZE = ONE_KB * 10;
    private static final IdGenerator<Integer> idGenerator = new IncreaseIntId();

    /**
     * ?URI?GETString?
     * 
     * @param uri
     *            URI
     * @return String
     * @throws IOException
     */
    public static String get(String uri) throws IOException {
        HttpGet request = new HttpGet(uri);
        return sendRequest(request);
    }

    /**
     * ?URI?GETString????
     *
     * @param uri
     *            URI
     * @return String?IOnull
     */
    public static String getIgnoreException(String uri) {
        HttpGet request = new HttpGet(uri);
        return sendRequestIgnoreException(request);
    }

    /**
     * ?get
     *
     * @param uri
     *            URI
     * @param l
     *            ??
     */
    public static void getAsync(final String uri, final HttpSimpleListener l) {
        HttpGet request = new HttpGet(uri);
        sendRequestAsyn(request, l);
    }

    /**
     * ?URI?POSTString?
     *
     * @param uri
     *            URI
     * @return String
     * @throws IOException
     */
    public static String post(String uri) throws IOException {
        HttpPost request = new HttpPost(uri);
        return sendRequest(request);
    }

    /**
     * ? URI?POSTString????
     *
     * @param uri
     *            URI
     * @return String?IOnull
     */
    public static String postIgnoreException(String uri) {
        HttpPost request = new HttpPost(uri);
        return sendRequestIgnoreException(request);
    }

    /**
     * ?POSTString?
     *
     * @param uri
     *            URI
     * @param params
     *            ?
     * @return String
     * @throws IOException
     */
    public static String post(String uri, BaseParams params) throws IOException {
        HttpPost request = new HttpPost(uri);
        if (params != null) {
            request.setEntity(new UrlEncodedFormEntity(params.getPairs()));
        }
        return sendRequest(request);
    }

    /**
     * ?post
     *
     * @param uri
     *            URI
     * @param params
     *            ?
     * @param l
     *            ??
     */
    public static void postAsync(String uri, BaseParams params, HttpSimpleListener l) {
        HttpPost request = new HttpPost(uri);
        sendRequestAsyn(request, params, l);
    }

    /**
     * ?post
     *
     * @param uri
     *            URI
     * @param l
     *            ?
     */
    public static void postAsync(final String uri, final HttpSimpleListener l) {
        HttpPost request = new HttpPost(uri);
        sendRequestAsyn(request, l);
    }

    /**
     * ?URI?PUT
     *
     * @param uri
     *            URI
     * @return 
     * @throws IOException
     */
    public static String put(String uri) throws IOException {
        HttpPut request = new HttpPut(uri);
        return sendRequest(request);
    }

    /**
     * ?PUT
     *
     * @param uri
     *            URI
     * @param params
     *            ?
     * @return 
     * @throws IOException
     */
    public static String put(String uri, BaseParams params) throws IOException {
        HttpPut request = new HttpPut(uri);
        if (params != null) {
            request.setEntity(new UrlEncodedFormEntity(params.getPairs()));
        }
        return sendRequest(request);
    }

    /**
     * ?URI?PUT???
     *
     * @param uri
     *            URI
     * @return ?null
     */
    public static String putIgnoreException(String uri) {
        HttpPut request = new HttpPut(uri);
        return sendRequestIgnoreException(request);
    }

    /**
     * ?URI?PUT
     *
     * @param uri
     *            URI.
     * @param l
     *            ???
     */
    public static void putAsync(final String uri, final HttpSimpleListener l) {
        HttpPut put = new HttpPut(uri);
        sendRequestAsyn(put, l);
    }

    /**
     * ?PUT
     *
     * @param uri
     *            URI
     * @param params
     *            ?
     * @param l
     *            ???
     */
    public static void putAsync(String uri, BaseParams params, HttpSimpleListener l) {
        HttpPut request = new HttpPut(uri);
        sendRequestAsyn(request, params, l);
    }

    /**
     * ?URI?DELETE
     *
     * @param uri
     *            URI.
     * @return 
     * @throws IOException
     */
    public static String delete(String uri) throws IOException {
        HttpDelete request = new HttpDelete(uri);
        return sendRequest(request);
    }

    /**
     * ?URI?DELETE???
     *
     * @param uri
     *            URI.
     * @return ?null
     */
    public static String deleteIgnoreException(String uri) {
        HttpDelete request = new HttpDelete(uri);
        return sendRequestIgnoreException(request);
    }

    /**
     * ?URI?DELETE
     *
     * @param uri
     *            URI.
     * @param l
     *            ??
     */
    public static void deleteAsync(String uri, HttpSimpleListener l) {
        HttpDelete request = new HttpDelete(uri);
        sendRequestAsyn(request, l);
    }

    /**
     * HTTP URIString
     *
     * @param request
     *            HTTP URI
     * @return String
     * @throws IOException
     *             ??IO
     */
    private static String sendRequest(HttpUriRequest request) throws IOException {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);
        return EntityUtils.toString(response.getEntity());
    }

    /**
     * HTTPString???
     *
     * @param request
     *            HTTP URI 
     * @return String?null
     */
    private static String sendRequestIgnoreException(HttpUriRequest request) {
        try {
            return sendRequest(request);
        } catch (final IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * HTTP 
     *
     * @param request
     *            ?
     */
    private static void sendRequestAsyn(HttpUriRequest request, HttpSimpleListener l) {
        HandlerFactory.newBackgroundHandler(idGenerator.next() + "").post(new RequestRunnable(request, l));
    }

    /**
     * HTTP
     *
     * @param request
     *            ?
     * @param params
     *            ?
     * @param l
     *            ??
     */
    private static void sendRequestAsyn(HttpUriRequest request, BaseParams params, HttpSimpleListener l) {
        HandlerFactory.newBackgroundHandler(idGenerator.next() + "")
                .post(new RequestRunnable(request, params.getPairs(), l));
    }

    /**
     * HttpRunnable
     *
     * @author msdx
     */
    static class RequestRunnable implements Runnable {
        private HttpUriRequest mRequest;
        private HttpSimpleListener mListener;
        private List<NameValuePair> mParams;

        RequestRunnable(HttpUriRequest request, HttpSimpleListener l) {
            mRequest = request;
            mListener = l;
        }

        public RequestRunnable(HttpUriRequest request, List<NameValuePair> params, HttpSimpleListener l) {
            mRequest = request;
            mParams = params;
            mListener = l;
        }

        @Override
        public void run() {
            try {
                if (mParams != null && mRequest instanceof HttpEntityEnclosingRequestBase) {
                    ((HttpEntityEnclosingRequestBase) mRequest).setEntity(new UrlEncodedFormEntity(mParams));
                }
                String result = sendRequest(mRequest);
                mListener.onFinish(result);
            } catch (final IOException e) {
                log.w(e.getMessage(), e);
                mListener.onFailed(e.getMessage());
            }
        }
    }

    /**
     * 
     *
     * @param url
     *            ?
     * @param savePath
     *            ??
     * @param overwrite
     *            ?
     * @throws IOException
     *             ??io
     */
    public static void download(String url, File savePath, boolean overwrite) throws IOException {
        if (savePath == null) {
            throw new IOException("the second parameter couldn't be null");
        }
        if (savePath.exists() && (!overwrite || savePath.isDirectory())) {
            throw new IOException("the file specified is exist or cannot be overwrite");
        }
        savePath.getParentFile().mkdirs();

        HttpURLConnection connection = null;
        InputStream input = null;
        FileOutputStream output = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            input = connection.getInputStream();
            output = new FileOutputStream(savePath);
            byte[] buffer = new byte[BUFFER_SIZE];
            int readSize = 0;
            while ((readSize = input.read(buffer)) != -1) {
                output.write(buffer, 0, readSize);
            }
            output.flush();
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 
     *
     * @param url
     *            ?
     * @param savePath
     *            ??
     * @param overwrite
     *            ?
     * @param listener
     *            ??
     */
    public static void downloadAsync(final String url, final File savePath, final boolean overwrite,
            final HttpSimpleListener listener) {
        final Handler handler = HandlerFactory.newBackgroundHandler(idGenerator.next() + "");
        final Runnable task = new Runnable() {

            @Override
            public void run() {
                try {
                    download(url, savePath, overwrite);
                    listener.onFinish(url);
                } catch (final IOException e) {
                    listener.onFailed(e.getMessage());
                    log.w(e.getMessage(), e);
                }
                handler.removeCallbacks(this);
            }
        };
        handler.post(task);
    }

    /**
     * HTTP??POST
     *
     * @param url
     *            ?URL
     * @param formName
     *            ?<input type="file" name="userfile" /> userfile
     * @param uploadFile
     *            
     * @return ?
     */
    public static String upload(String url, String formName, String uploadFile) {
        return upload(url, formName, new File(uploadFile));
    }

    /**
     * HTTP??POST
     *
     * @param url
     *            ?URL
     * @param formName
     *            ?<input type="file" name="userfile" /> userfile
     * @param uploadFile
     *            
     * @return ?
     */
    public static String upload(String url, String formName, File uploadFile) {
        SimpleMultipartEntity entity = new SimpleMultipartEntity(); // 
        entity.addPart(formName, uploadFile, true);
        try {
            return doUpload(url, entity);
        } catch (final IOException e) {
            log.w(e.getMessage(), e);
        }
        return null;
    }

    /**
     * HTTP??POST??
     *
     * @param url
     *            ?URL
     * @param entity
     *            
     * @return ?
     */
    public static String upload(String url, SimpleMultipartEntity entity) {
        try {
            return doUpload(url, entity);
        } catch (final IOException e) {
            log.w(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 
     *
     * @param url
     *            ?URL
     * @param entity
     *            
     * @return ?
     * @throws ClientProtocolException
     * @throws IOException
     */
    private static String doUpload(String url, SimpleMultipartEntity entity)
            throws ClientProtocolException, IOException {
        HttpClient httpclient = null;
        try {
            httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(entity);
            HttpResponse response;
            response = httpclient.execute(httppost);
            return EntityUtils.toString(response.getEntity());
        } finally {
            if (httpclient != null) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }

    /**
     * 
     *
     * @param url
     *            URL
     * @param formName
     *            ?<input type="file" name="userfile" /> userfile
     * @param uploadFile
     *            
     * @param listener
     *            ??
     */
    public static void uploadAsync(final String url, final String formName, final File uploadFile,
            final HttpSimpleListener listener) {
        HandlerFactory.newBackgroundHandler(idGenerator.next() + "").post(new Runnable() {

            @Override
            public void run() {
                SimpleMultipartEntity entity = new SimpleMultipartEntity(); // 
                entity.addPart(formName, uploadFile, true);
                try {
                    listener.onFinish(doUpload(url, entity));
                } catch (final IOException e) {
                    log.w(e.getMessage(), e);
                    listener.onFailed(e.getMessage());
                }
            }
        });
    }

    /**
     * 
     *
     * @param url
     *            ?URL
     * @param entity
     *            
     * @param listener
     *            ??
     */
    public static void uploadAsync(final String url, final SimpleMultipartEntity entity,
            final HttpSimpleListener listener) {
        HandlerFactory.newBackgroundHandler(idGenerator.next() + "").post(new Runnable() {

            @Override
            public void run() {
                try {
                    listener.onFinish(doUpload(url, entity));
                } catch (final IOException e) {
                    log.w(e.getMessage(), e);
                    listener.onFailed(e.getMessage());
                }
            }
        });
    }

    /**
     * ?GET?
     *
     * @param uri
     *            URI
     * @return inputStream
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static InputStream getInputStream(final String uri) throws ClientProtocolException, IOException {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        return response.getEntity().getContent();
    }

    /**
     * bitmap
     * 
     * @param uri
     *            url
     * @return ?bitmap???null
     */
    public static Bitmap getBitmap(final String uri) {
        InputStream is = null;
        try {
            is = getInputStream(uri);
            return BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            log.w(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
        return null;
    }
}