Does Android Wear support HttpURLConnection - gett

2020-02-26 08:28发布

问题:

I am wondering if we can access the network through HttpURLConnection from Android Wear?

I tried using HttpURLConnection inside Wear code, I am getting EOFException. The same code works from regular Android phone. It only has problem when it is on Android Wear.

If HttpURLConnection is not supported on Wear, should we use Apache Http client or something else?

Or perhaps the way I am launching the app for development is incorrect?

        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect(); 
        int response = conn.getResponseCode(); 

I did add the permission into android manifest. I also run the above code from an AsyncTask.

EOFException occurs at conn.getResponseCode().

java.io.EOFException
        at com.android.okhttp.internal.Util.readAsciiLine(Util.java:342)
        at com.android.okhttp.internal.http.RawHeaders.fromBytes(RawHeaders.java:311)
        at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:135)
        at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:644)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:353)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:297)
        at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:509)

Thank you very much for your help.

回答1:

Unfortunately, no.

Android Wear applications cannot directly access the Internet. They must communicate with their corresponding handheld app (either via MessageApi or DataApi) and request that it executes whatever HTTP requests you need.


EDIT: Android Wear 2.0, now in beta, supports network requests, so HttpURLConnection should work there.