使用 HttpURLConnection 读取 REST 请求输出

Reading REST Request Output using HttpURLConnection

我正尝试在 java 上的 StackExchange API 上执行 REST 请求,但我在读取输出时遇到了一些问题。我做了一个小代码示例,看看我是否可以正确阅读:

package Utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClient
{


public static void main(String[] args)
{
    try
    {
        URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=Whosebug");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        System.out.println(conn.getResponseCode());

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String output;

        while ((output = reader.readLine()) != null)
        {
            System.out.println(output);
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

}

以下是网站的示例输出:

{"items":[{"tags":["c++","templates","covariant"],"owner":{"reputation":3,"user_id":7447292,"user_type":"registered","profile_image":"https://www.gravatar.com/avatar/8979f1b328b9b0f786dec8b4edd514bc?s=128&d=identicon&r=PG&f=1","display_name":"B.Oudot","link":"http://whosebug.com/users/7447292/b-oudot"}

然而,当我打印 java 程序的输出时,我得到状态代码 200,然后剩下的只是一堆非 ascii 字符。我是 REST 和 JSON 的新手。如果可能,我不想使用任何第三方库。

编辑 我已将程序的输出作为图像。

当内容编码使用 gZip 时,您需要使用 GZIPInputStream api。它也是一个输入流。

我对你的响应使用了 gipinput 流,我在 json 中看到了输出。

public static void main(String[] args){
    try
    {
        URL url = new URL("https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=Whosebug");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        System.out.println(conn.getResponseCode());



        GZIPInputStream gzis = new GZIPInputStream(conn.getInputStream());
        InputStreamReader reader = new InputStreamReader(gzis);
        BufferedReader in = new BufferedReader(reader);

        String readed;
        while ((readed = in.readLine()) != null) {
            System.out.println(readed);
        }
        //BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String output;

        while ((output = in.readLine()) != null)
        {
            System.out.println(output);
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    }

对我有用。