pl.wasyl.mpkmaps.HttpClient.java Source code

Java tutorial

Introduction

Here is the source code for pl.wasyl.mpkmaps.HttpClient.java

Source

/***
   Copyright (c) 2009 
   Author: Stefan Klumpp <stefan.klumpp@gmail.com>
   Web: http://stefanklumpp.com
    
   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 pl.wasyl.mpkmaps;

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

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;

public class HttpClient extends AsyncTask<Pair<String, JSONObject>, Void, JSONArray> {

    public interface AsyncResponse {
        void processFinished(JSONArray result);
    }

    private static final String TAG = "HttpClient";
    JSONObject rv;
    AsyncResponse sender;

    public HttpClient(AsyncResponse sender) {
        this.sender = sender;
    }

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         * 
         * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    @Override
    protected JSONArray doInBackground(Pair<String, JSONObject>... params) {
        String URL = params[0].first;
        JSONObject jsonObjSend = params[0].second;
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPostRequest = new HttpPost(URL);

            StringEntity se;
            se = new StringEntity(jsonObjSend.toString());

            // Set HTTP parameters
            httpPostRequest.setEntity(se);
            httpPostRequest.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            httpPostRequest.setHeader("Accept-Charset", "ISO-8859-2,utf-8;q=0.7,*;q=0.3");
            httpPostRequest.setHeader("Accept-Encoding", "gzip,deflate,sdch");
            httpPostRequest.setHeader("Accept-Language", "pl,en-US;q=0.8,en;q=0.6,en-GB;q=0.4");
            httpPostRequest.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPostRequest.setHeader("X-Requested-With", "XMLHttpRequest");
            //httpPostRequest.setHeader("Host", "pasazer.mpk.wroc.pl");
            //httpPostRequest.setHeader("Origin", "http://pasazer.mpk.wroc.pl");
            //httpPostRequest.setHeader("Referer", "http://pasazer.mpk.wroc.pl/jak-jezdzimy/mapa-pozycji-pojazdow");
            //httpPostRequest.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
            //

            long t = System.currentTimeMillis();
            HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
            Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

            // Get hold of the response entity (-> the data):
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                // Read the content stream
                InputStream instream = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    instream = new GZIPInputStream(instream);
                }

                // convert content stream to a String
                String resultString = convertStreamToString(instream);
                Log.i(TAG, "<ResultString:>\n" + resultString + "\n</ResultString>");
                instream.close();
                //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

                // Transform the String into a JSONObject
                JSONArray jsonObjRecv = new JSONArray(resultString);
                // Raw DEBUG output of our received JSON object:
                Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
                return jsonObjRecv;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        sender.processFinished(result);
    }
}