0

HttpURLConnection を読み取る方法を理解しようとしています。この例: http://www.vogella.com/tutorials/AndroidNetworking/article.htmlによると、次のコードが機能するはずです。ただし、 readStream は起動せず、行もログに記録していません。

私は InputStream がバッファとすべてを介して渡されることを理解していますが、私の場合、論理は readStream メソッドで壊れ、ほとんどが空の文字列 'line' と while ステートメントです。そこで何が起こっているのか、そこで何が起こるべきなのか、どうすれば修正できるのでしょうか? また、Try ステートメントで URL を作成する必要があるのはなぜですか? 未処理の例外が返されます。java.net.MalformedURLException.

前もって感謝します!

static String SendURL(){
    try {
        URL url = new URL("http://www.google.com/");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
          readStream (con.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return ("Done");

}

static void readStream(InputStream in) {

    BufferedReader reader = null;

    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            Log.i("Tag", line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
4

2 に答える 2

0

質問に投稿したコードには多くの問題があります。これが実際の例です:

public class GooglePlaces extends AsyncTask {

public InputStream inputStream;


    public GooglePlaces(Context context) {

        String url = "https://www.google.com";


        try {
            HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
            HttpResponse httpResponse = httpRequest.execute();
            inputStream = httpResponse.getContent();

        } catch (IOException e) {
            e.printStackTrace();
        }


        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder builder = new StringBuilder();

        try {
            for (String line = null; (line = bufferedReader.readLine()) != null;) {
                builder.append(line).append("\n");
                Log.i("GooglePlacesTag", line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
于 2014-03-25T00:49:23.500 に答える