Java tutorial
//package com.java2s; /** * Copyright (c) 2015, 2016 IBM Corporation. All rights reserved. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; public class Main { /** * Extract the body of an HTTP response as a string. * @param connection the connection to read from. * @return the string extracted from the connection's input stream. * @throws Exception if any error occurs. */ static String readResponseBody(HttpURLConnection connection) throws Exception { return readString(new BufferedInputStream(connection.getInputStream())); } /** * Read a string content from a stream. * @param in the stream to read from. * @return the string extracted frm the stream. * @throws Exception if any error occurs. */ static String readString(InputStream in) throws Exception { return new String(readBytes(in), "utf-8"); } /** * Read bytes from an HTTP connection. * @param connection the connection to read from. * @return an array of the bytes read. * @throws Exception if any error occurs. */ static byte[] readBytes(HttpURLConnection connection) throws Exception { return readBytes(new BufferedInputStream(connection.getInputStream())); } /** * Read a string content from a stream. * @param in the stream to read from. * @return the raw bytes extracted from the stream. * @throws Exception if any error occurs. */ static byte[] readBytes(InputStream in) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int n; while ((n = in.read(buffer)) > 0) { out.write(buffer, 0, n); } out.close(); return out.toByteArray(); } }