Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform OkHttp network actions in background thread

I am using OKHttp to perform Post request to server, as follow:

public class NetworkManager {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    String post(String url, JSONObject json) throws IOException {
        try {
            JSONArray array = json.getJSONArray("d");
            RequestBody body = new FormEncodingBuilder()
                    .add("m", json.getString("m"))
                    .add("d", array.toString())
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (JSONException jsone) {
            return "ERROR: " + jsone.getMessage();
        }
    }
}

and call it with:

NetworkManager manager = new NetworkManager();
String response = manager.post("http://www.example.com/api/", jsonObject);

When I try to run the App, it prompts an error in the logcat:

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)

With reference to other questions in SO, I added this to override the policy:

if (android.os.Build.VERSION.SDK_INT > 9)
{
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
}

Yet I think this is unhealthy and I would like to put the NetworkManager actions to background. How can I do so?

like image 979
Raptor Avatar asked Dec 18 '22 21:12

Raptor


1 Answers

Since OkHttp supports async way too, so IMO you can refer to the following GET request sample, then apply for your POST request:

        OkHttpClient client = new OkHttpClient();
        // GET request
        Request request = new Request.Builder()
                .url("http://google.com")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e(LOG_TAG, e.toString());
            }
            @Override
            public void onResponse(Response response) throws IOException {
                Log.w(LOG_TAG, response.body().string());
                Log.i(LOG_TAG, response.toString());
            }
        });

Hope it helps!

like image 126
BNK Avatar answered Dec 27 '22 13:12

BNK