com.kkurahar.locationmap.HttpConnection.java Source code

Java tutorial

Introduction

Here is the source code for com.kkurahar.locationmap.HttpConnection.java

Source

/*
 * Copyright (C) 2012 kkurahar
 *
 * 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.kkurahar.locationmap;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpConnection {
    public String doGet(String url) {

        HttpGet method = new HttpGet(url);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        method.setHeader("Connection", "Keep-Alive");
        try {

            String resultRes = httpClient.execute(method, new ResponseHandler<String>() {

                @Override
                public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    // Xe?[^XR?[h
                    int status = response.getStatusLine().getStatusCode();
                    if (HttpStatus.SC_OK == status) {
                        Header[] headers = response.getAllHeaders();
                        for (Header h : headers) {
                            System.out.println(h.getName() + ":" + h.getValue());
                        }
                    } else {
                        throw new RuntimeException("?MG?[?");
                    }
                    return EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            });
            return resultRes;
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

    }

}