Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

public class Main {
    private static final int REQUEST_TIMEOUT = 20 * 1000;
    private static final int SO_TIMEOUT = 20 * 1000;

    public static String getHttpClientString(String path) {
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpParams);
        DefaultHttpClient httpClient = (DefaultHttpClient) client;
        HttpResponse httpResponse = null;
        String result = "";
        try {
            httpResponse = httpClient.execute(new HttpGet(path));
            int res = httpResponse.getStatusLine().getStatusCode();
            if (res == 200) {
                InputStream in = httpResponse.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line.trim());
                }
                reader.close();
                in.close();
                result = sb.toString();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }
}