Converts the input stream from a url connection into a response string. - Android File Input Output

Android examples for File Input Output:InputStream

Description

Converts the input stream from a url connection into a response string.

Demo Code


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

import java.io.UnsupportedEncodingException;

public class Main {
    /**//  w  w  w  . j av  a 2  s  . c o  m
     * Converts the input stream from a url connection into a response string.
     * 
     * Reference: <a href="http://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection">http://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection</a> on Oct 23, 2014, User Mihai Todor
     * 
     * @param stream                  The stream to read from.
     * @return                        The response as a string.
     * @throws IOException               Exception thrown on any failure to read from stream.
     * @throws UnsupportedEncodingException   Expceptino thrown on any non-recognized encoding type. 
     */
    private static String readResponse(InputStream stream)
            throws IOException, UnsupportedEncodingException {
        BufferedReader responseStreamReader = new BufferedReader(
                new InputStreamReader(stream));
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = responseStreamReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        responseStreamReader.close();

        String response = stringBuilder.toString();
        return response;
    }
}

Related Tutorials