2017-03-11 16 views
0

ウェブページの「ソースコードを見る」必要があるアプリを作っていました。だから私はこのスクリプトを最初に作った:ウェブページからコンテンツを取得できません

public static String getResponseFromUrl(@NonNull String url) throws java.io.IOException { 
    HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
    HttpGet httpget = new HttpGet(URL); // Set the action you want to do 
    HttpResponse response = httpclient.execute(httpget); // Executeit 
    HttpEntity entity = response.getEntity(); 
    InputStream is = entity.getContent(); // Create an InputStream with the response 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) 
     sb.append(line); 
    String resString = sb.toString(); 
    is.close(); 
    return resString; 
} 

しかし、私はHttpClientが非難されていることに気づいた。だから、いくつかの検索の後、私は、私がのHttpURLConnectionを使用する必要がことがわかったAsyncTaskの内側に、そして、私は、スクリプトを作っ:

public class CodeTask extends AsyncTask<String, Integer, String> { 

    @Override 
    protected String doInBackground(String... urls) { 
     try { 
      HttpURLConnection urlConnection = null; 
      String toRet = ""; 
      URL url = new URL(urls[0]); 
      try { 
       urlConnection = (HttpURLConnection) url.openConnection(); 

       if (urlConnection.getContent() != null) { 
        InputStreamReader in = new InputStreamReader((InputStream) urlConnection.getContent()); 
        toRet = IOUtils.toString(in); 
        Debug(toRet); 
       } else 
        Debug("urlConnection is null"); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       if (urlConnection != null) 
        urlConnection.disconnect(); 
      } 
      return toRet; 
     }catch (Exception ex){ 
      ex.printStackTrace(); 
     } 
     return null; 
    } 
} 

そして、私はインスタンスを作成します。

CodeTask codeTask = new CodeTask(); 

しかし、私は次のような応答を得ようとします:

しかし、それはAsyncTaskを返します。私は何をしなければならないのですか?

答えて

0

最後に.get()を追加するだけで、String値が返されます。

関連する問題