Suggested Pages

Friday, January 13, 2017

OkHttp NetworkOnMainThreadException

OkHttp Code
    RequestBody body = RequestBody.create(JSON, jsonString); 
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = client.newCall(request).execute();
    response.body().string();
If you have this problem:
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
        at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1009)
        at com.squareup.okhttp.Connection.closeIfOwnedBy(Connection.java:136)
        at com.squareup.okhttp.OkHttpClient$1.closeIfOwnedBy(OkHttpClient.java:70)
        at com.squareup.okhttp.internal.http.HttpConnection.closeIfOwnedBy(HttpConnection.java:134)
Possible solution:

    private class AsyncExample extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
               RequestBody body = RequestBody.create(JSON, jsonString); 
               Request request = new Request.Builder().url(url).post(body).build();
               Response response = client.newCall(request).execute();
               response.body().string();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

No comments :

Post a Comment

Suggested Pages