2017-08-02 77 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