在后台线程中执行OkHttp网络操作

Rap*_*tor 2 java android okhttp

我正在使用OKHttp对服务器执行Post请求,如下所示:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

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

当我尝试运行App时,它会在logcat中提示错误:

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

参考SO中的其他问题,我添加了这个以覆盖策略:

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

但我认为这是不健康的,我想把这些NetworkManager行动置于背景之下.我怎么能这样做?

BNK*_*BNK 7

由于OkHttp也支持异步方式,因此IMO可以参考以下GET请求示例,然后申请POST请求:

        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());
            }
        });
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 如你所见,在`onResponse`里面你会这样做,如果你想更新UI或显示Toast,你还需要`mHandler = new Handler(Looper.getMainLooper());`.如果请求在另一个类(例如Utils.java)中,我认为你应该使用一个监听器接口 (2认同)
  • 你可以参考我的GitHub示例项目,它是一个POST请求。https://github.com/ngocchung/MultipartOkHttp (2认同)