質問

I've been trying to figure out how to read a HttpURLConnection. According to this example: http://www.vogella.com/tutorials/AndroidNetworking/article.html , the following code should work. However, readStream never fires, and I'm not logging any lines.

I do get that the InputStream is passed through the buffer and all, but for me the logic breaks down in the readStream method, and then mostly the empty string 'line' and the while statement. What exactly is happening there / should happen there, and how would I be able to fix it? Also, why do I have to create the url in the Try statement? It gives back a Unhandled Exception; java.net.MalformedURLException.

Thanks in advance!

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();
            }
        }
    }
}
役に立ちましたか?

解決

There are a bunch of things wrong with the code I posted in the question. Here is a working example:

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

他のヒント

It appears you are not connecting your HTTPUrlClient try con.connect()

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top