Whole HTTP response as String from given URLConnection - Java Network

Java examples for Network:URL

Description

Whole HTTP response as String from given URLConnection

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import java.net.URLConnection;

public class Main {
    /**/* w  ww.  j  av a2  s.c  o m*/
     * Whole HTTP response as String from given URLConnection
     *
     * @param connection
     * @return whole HTTP response as String
     */
    public static String readUrlContent(URLConnection connection) {
        StringBuilder result = new StringBuilder();
        try {
            Reader reader = new InputStreamReader(
                    connection.getInputStream());
            char[] buffer = new char[50];
            int nrOfChars;
            while ((nrOfChars = reader.read(buffer)) != -1) {
                result.append(buffer, 0, nrOfChars);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result.toString();
    }
}

Related Tutorials