get Response Body from URL - Android Network

Android examples for Network:HTTP Response

Description

get Response Body from URL

Demo Code


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

import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static String getResponseBody(String url) {
        String result = null;/*from w ww. j a  v a 2 s.c o m*/
        URL urlO = null;
        HttpURLConnection http = null;
        InputStream is = null;
        try {
            urlO = new URL(url);
            http = (HttpURLConnection) urlO.openConnection();
            http.addRequestProperty("Cache-Control", "no-cache");
            http.addRequestProperty("Connection", "keep-alive");
            http.setConnectTimeout(5 * 1000);
            http.setReadTimeout(10 * 1000);
            http.connect();
            int code = http.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                is = http.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int ch;
                byte[] buffer = new byte[2048];
                while ((ch = is.read(buffer)) != -1) {
                    out.write(buffer, 0, ch);
                    out.flush();
                }
                // ?????????????
                result = out.toString();
                out.close();
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            if (null != http) {
                http.disconnect();
            }
        }
        return result;
    }

    public static String getResponseBody(String url, String charset) {
        String result = null;
        URL urlO = null;
        HttpURLConnection http = null;
        InputStream is = null;
        try {
            urlO = new URL(url);
            http = (HttpURLConnection) urlO.openConnection();
            http.addRequestProperty("Cache-Control", "no-cache");
            http.addRequestProperty("Connection", "keep-alive");
            http.setConnectTimeout(5 * 1000);
            http.setReadTimeout(10 * 1000);
            http.connect();
            int code = http.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                is = http.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int ch;
                byte[] buffer = new byte[2048];
                while ((ch = is.read(buffer)) != -1) {
                    out.write(buffer, 0, ch);
                    out.flush();
                }
                result = out.toString(charset);
                out.close();
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            if (null != http) {
                http.disconnect();
            }
        }
        return result;
    }
}

Related Tutorials