2017-08-02 54 views
0

我想通过使用简单的HTTP请求和Java中的GET方法从stackoverflow api获取我的用户信息。如何从HTTP请求中获取正确的数据

此代码我用了之前得到用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变种,像这样:

�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ͺ}�\����� 

在此先感谢。

回答

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

+0

这是正确的! – jorrin

+0

谢谢这是正确的方法:) – HCarrasko