使用HttpURLConnection读取REST请求输出

时间:2017-03-29 16:14:31

标签: java json rest httpresponse stackexchange

我正在尝试在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=stackoverflow");
        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://stackoverflow.com/users/7447292/b-oudot"}

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

EDIT 我把程序的输出作为图像。

Non Ascii Chatacters

1 个答案:

答案 0 :(得分:1)

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

我在你的回复中使用了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=stackoverflow");
        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();
    }

    }

它对我有用。