Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;

import org.apache.http.StatusLine;

import org.apache.http.util.EncodingUtils;

public class Main {
    private static final int HTTP_STATUS_OK = 200;
    private static byte[] buff = new byte[1024];

    public static String responseAsString(HttpResponse response) throws IOException {

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            throw new IOException("Invalid response from server! " + status.toString());
        }

        //do the herdy gerdy and convert the response to a String
        InputStream ist = response.getEntity().getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();
        int readCount = 0;
        while ((readCount = ist.read(buff)) != -1)
            content.write(buff, 0, readCount);

        String thePagesContent = EncodingUtils.getString(content.toByteArray(), "UTF-8");

        return thePagesContent;
    }
}