2016-08-20 91 views
0

我有一箇舊的代碼執行與DefaultHttpClient的http請求,我試圖將其轉換爲HttpURLConnection,但我有麻煩的響應。HttpURLConnection返回響應像DefaultHttpClient

這裏是原代碼:

private InputStream fetch(String urlString) throws MalformedURLException, IOException { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpGet request = new HttpGet(urlString); 
      HttpResponse response = httpClient.execute(request); 
      return response.getEntity().getContent(); 
     } 

這裏是我想要做的事:

HttpURLConnection conn = null; 
    URL url; 
    try 
    { 
     url = new URL(serviceUrl); 
    } 
    catch (MalformedURLException e) 
    { 
     throw new IllegalArgumentException("invalid url: " + serviceUrl); 
    } 

    try { 

     conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setUseCaches(false); 
     conn.setRequestMethod("GET"); 
     conn.setRequestProperty("Content-Type", "application/json"); 
     conn.connect(); 
     //Don't know what to do now to return the response(?) 
    } 

但我不知道如何做到這一點得到了相同的結果與迴應一樣。

+0

使用'conn.getInputStream()' – Enzokie

+0

你想要一個方法**獲得**響應? –

+0

@Enzokie ok,thkk – PaulD

回答

0

您可以使用以下方法:

InputStream inputStream = conn.getInputStream(); 
StringBuilder build = new StringBuilder(); 
    if (inputStream != null) { 
     InputStreamReader ISreader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); 
     BufferedReader reader = new BufferedReader(ISreader); 
     String line = reader.readLine(); 
     while (line != null) { 
      build.append(line); 
      line = reader.readLine(); 
     } 
    } 
return build.toString(); 

在這段代碼中,你是從HttpUrlConnection,這是用來獲取使用InputStreamReaderBufferedReader響應得到InputStream

+0

好的,thnks。 下次肯定會幫助我,但現在我只需要輸入流。 – PaulD

+0

沒問題。如果這回答了您的問題,請接受此答案 –