Processes an HTTP request. - Android Network

Android examples for Network:HTTP Request

Description

Processes an HTTP request.

Demo Code

/*//from  www.  ja  v  a  2 s. c  o  m
 * Copyright 2012 emuneee apps
 * http://emuneee.com/apps
 *
 * 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.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import android.util.Log;

public class Main {
    public final static String TAG = "HttpUtils";
    private static int BUFFER_SIZE = 4096;

    /**
     * Processes an HTTP request. Expects string data as the result
     * @param request
     * @return
     */
    public static String processHttpRequest(HttpURLConnection urlConnection)
            throws IOException {
        final StringBuilder retVal;
        BufferedReader bReader = null;
        InputStreamReader iReader = null;
        String line;

        retVal = new StringBuilder();
        try {
            bReader = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()), BUFFER_SIZE);
            while ((line = bReader.readLine()) != null) {
                retVal.append(line);
            }
            Log.v(TAG, "Content Size: " + retVal.length());
            Log.v(TAG, "Response Code: " + urlConnection.getResponseCode());
        } catch (IOException e) {
            Log.w(TAG, e.getMessage());
            return null;
        } finally {
            if (iReader != null)
                iReader.close();
            if (bReader != null)
                bReader.close();
            urlConnection.disconnect();
        }

        return retVal.toString();
    }
}

Related Tutorials