2016-08-20 7 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(?) 
    } 

しかし、私は同じ結果を得るためにどのように行うのか分かりません応答と同様に。このコードで

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(); 

、あなたがInputStreamReaderBufferedReaderを使用して応答を取得するために使用されHttpUrlConnection、からInputStreamを得ている:

+0

'conn.getInputStream()' – Enzokie

+0

を使用すると、メソッドで**レスポンスを**取得できますか? –

+0

@Enzokie ok、thnks – PaulD

答えて

0

は、次を使用することができます。

+0

Ok、thnks。 これは確かに次回に役立ちますが、今は入力ストリームが必要でした。 – PaulD

+0

問題ありません。これがあなたの質問に答えた場合は、この回答を受け入れてください –

関連する問題