如何从HTTP请求中获取正确的数据

时间:2017-08-02 00:35:58

标签: java http get request

我正在尝试使用Java中的GET方法使用简单的HTTP请求从stackoverflow api获取我的用户信息。

我之前用过的代码使用GET方法获取另一个HTTP数据没有问题:

    URL obj;
    StringBuffer response = new StringBuffer();
    String url = "http://api.stackexchange.com/2.2/users?inname=HCarrasko&site=stackoverflow";
        try {
        obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();
        System.out.println(response.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

但是在这种情况下,当我打印response var时,我会得到更奇怪的符号,如下所示:

�mRM��0�+�N!���FZq�\�pD�z�:V���JX���M��̛yO^���뾽�g�5J&� �9�YW�%c`do���Y'��nKC38<A�&It�3��6a�,�,]���`/{�D����>6�Ɠ��{��7tF ��E��/����K���#_&�yI�a�v��uw}/�g�5����TkBTķ���U݊c���Q�y$���$�=ۈ��ñ���8f�<*�Amw�W�ـŻ��X$�>'*QN�?�<v�ݠ FH*��Ҏ5����ؔA�z��R��vK���"���@�1��ƭ5��0��R���z�ϗ/�������^?r��&�f��-�OO7���������Gy�B���Rxu�#:0�xͺ}�\�����

提前感谢。

1 个答案:

答案 0 :(得分:3)

内容可能是GZIP编码/压缩的。以下是我在所有使用HTTP的基于Java的客户端应用程序中使用的一般代码片段,旨在解决此问题:

// Read in the response
// Set up an initial input stream:
InputStream inputStream = fetchAddr.getInputStream(); // fetchAddr is the HttpURLConnection

// Check if inputStream is GZipped
if("gzip".equalsIgnoreCase(fetchAddr.getContentEncoding())){
    // Format is GZIP
    // Replace inputSteam with a GZIP wrapped stream
    inputStream = new GZIPInputStream(inputStream);
}else if("deflate".equalsIgnoreCase(fetchAddr.getContentEncoding())){
    inputStream = new InflaterInputStream(inputStream, new Inflater(true));
} // Else, we assume it to just be plain text

BufferedReader sr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
// ... and from here forward just read the response...

这取决于以下导入:java.util.zip.GZIPInputStream; java.util.zip.Inflater;和java.util.zip.InflaterInputStream