如何从AsyncTask切换到OkHTTP,理想的方法?

时间:2018-08-16 18:31:24

标签: android android-asynctask okhttp3

以前没有探索过OkHttp,使用AsyncTask进行的网络通话目前可以正常工作,但出于其他要求,希望切换到OkHttp

这是我使用AsyncTask进行网络通话的方式:

   private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        // params comes from the execute() call: params[0] is the url.
        try {
            try {
                return HttpPost(urls[0]);
            } catch(Exception e) {
                e.printStackTrace();
                return "Error!";
            }
        } catch (Exception e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Log.d("data is being sent",result);
    }
}
private String HttpPost(String myUrl) throws IOException {
    String result = "";

    URL url = new URL(myUrl);

    // 1. create HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(StringData);
    writer.flush();
    writer.close();
    os.close();

    // 4. make POST request to the given URL
    conn.connect();

    // 5. return response message
    return conn.getResponseMessage()+"";

}

现在,如何使用POST进行相同的OkHttp调用,这就是我的位置:

private void makeNetworkCall()
{
    OkHttpClient client=new OkHttpClient();
    Request request=new Request.Builder().url(post_url).build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e)
        {

            Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            Log.e("TAG","SUCCESS");
        }
    });
}

但是,不确定如何使用OkHttp方式传递数据,我们将不胜感激。感谢您。

2 个答案:

答案 0 :(得分:0)

诚实,我什至不会打扰普通的OkHttp Retrofit,它是您选择的工具,它用途广泛(甚至支持类似Rx的样式),并且减轻了许多您必须处理的低级内容现在。

要进一步提高技能,请看this

答案 1 :(得分:0)

我同意这样的答案,从长远来看,如果计划对后端进行许多不同的网络调用,则从长远来看翻新会更好。但是,如果您坚持在较低级别使用OkHttp,则可以执行以下操作:

String jsonString = json.toString();
RequestBody body = RequestBody.create(JSON, jsonString);

Request request = new Request.Builder()
    .header("Content-Type", "application/json; charset=utf-8")
    .url(post_url)
    .post(body)
    .build();

client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
    @Override
    public void onFailure(Request request, IOException throwable) {

    }

    @Override
    public void onResponse(Response response) throws IOException {

    }
});