集册 Java实例教程 整个HTTP响应作为给定URLConnection的字符串

整个HTTP响应作为给定URLConnection的字符串

欢马劈雪     最近更新时间:2020-01-02 10:19:05

453
来自给定URLConnection的整个HTTP响应作为字符串


//package com.nowjava;

import java.io.IOException;

import java.io.InputStreamReader;/* from N  o w  J a v a . c o m*/

import java.io.Reader;


import java.net.URLConnection;


public class Main {

    /**

     * 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;/** 来 自 N o w J a v a . c o m - 时  代  Java**/

            while ((nrOfChars = reader.read(buffer)) != -1) {

                result.append(buffer, 0, nrOfChars);

            }
展开阅读全文