Java HTTP Response readResponse(HttpURLConnection connection)

Here you can find the source of readResponse(HttpURLConnection connection)

Description

read Response

License

Open Source License

Declaration

public static byte[] readResponse(HttpURLConnection connection) throws IOException 

Method Source Code


//package com.java2s;
/*//w  ww  . j ava  2  s. co m
 * Copyright (c) 2016 "JackWhite20"
 *
 * This file is part of Cobra.
 *
 * Cobra is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.*;
import java.net.HttpURLConnection;

public class Main {
    public static final int CHUNK_SIZE = 2048;

    public static byte[] readResponse(HttpURLConnection connection) throws IOException {

        boolean error = connection.getResponseCode() >= 400;

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                InputStream inputStream = (!error) ? connection.getInputStream() : connection.getErrorStream()) {
            byte[] chunk = new byte[CHUNK_SIZE];

            int i;
            while ((i = inputStream.read(chunk)) > 0) {
                byteArrayOutputStream.write(chunk, 0, i);
            }

            return byteArrayOutputStream.toByteArray();
        }
    }
}

Related

  1. getResponseStream(HttpURLConnection conn)
  2. getResponseStringFromConn(HttpURLConnection conn, boolean isSuccess)
  3. getResponseText(URL constructedUrl, String encoding)
  4. getResposeText(HttpURLConnection connection)
  5. readResponse(HttpURLConnection conn, String encoding)
  6. readResponse(HttpURLConnection httpURLConnection)
  7. readResponse(URLConnection conn)