com.imellon.android.grocerymate.util.HttpManager.java Source code

Java tutorial

Introduction

Here is the source code for com.imellon.android.grocerymate.util.HttpManager.java

Source

/*
 * Copyright (C) 2008 Romain Guy
 *
 * 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.imellon.android.grocerymate.util;

import org.apache.http.params.HttpParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ClientConnectionManager;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

public class HttpManager {
    private static final DefaultHttpClient sClient;
    private static final String TAG = HttpManager.class.getSimpleName();
    static {
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);

        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
        HttpConnectionParams.setSoTimeout(params, 20 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        ConnManagerParams.setTimeout(params, 1000);
        // http://androidisland.blogspot.com/2010/11/httpclient-and-connectionpooltimeoutexc.html
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
            @Override
            public int getMaxForRoute(HttpRoute route) {
                // TODO Auto-generated method stub
                return 20;
            }
        });

        HttpClientParams.setRedirecting(params, false);

        HttpProtocolParams.setUserAgent(params, "GroceryMate/1.1");

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
        sClient = new DefaultHttpClient(manager, params);
    }

    private HttpManager() {
    }

    public static HttpResponse execute(HttpGet get) throws IOException {
        return sClient.execute(get);
    }

    public static InputStream downloadFromUrl(String url) throws IOException {
        Log.d(TAG, "downloading " + url);

        HttpGet request = new HttpGet(url);
        request.setHeader("Accept-Encoding", "gzip");
        request.setHeader("Accept", "application/json");
        return executeRequest(request);
    }

    /**
     * Executes an HTTP request on a REST web service. If the response is ok, the content
     * is sent to the specified response handler.
     *
     * @param host
     * @param get The GET request to executed.
     * @param handler The handler which will parse the response.
     *
     * @throws java.io.IOException
     */
    private static InputStream executeRequest(HttpGet get) throws IOException {

        HttpEntity entity = null;
        //        try {
        final HttpResponse response = HttpManager.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = response.getEntity();
            InputStream in = entity.getContent();
            if (response.containsHeader("Content-Encoding")
                    && response.getFirstHeader("Content-Encoding").getValue().equalsIgnoreCase("gzip")) {
                in = new GZIPInputStream(in);
            }
            return in;
        }
        return null;
        //        } finally {
        //            if (entity != null) {
        //                entity.consumeContent();
        //            }
        //        }
    }

    public static String convertInputStreamToString(InputStream ginstream) throws IOException {
        StringBuffer theText = new StringBuffer();

        if (ginstream != null) {
            InputStreamReader reader = new InputStreamReader(ginstream);
            BufferedReader in = new BufferedReader(reader);
            String readed;

            while ((readed = in.readLine()) != null) {
                theText.append(readed + "\n");
            }
            ginstream.close();
        }

        return theText.toString();
    }
}