0

之前没有探索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方式传递数据,任何帮助将不胜感激。感谢您。

4

2 回答 2

0

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

为了进一步提高你的技能,看看这个

于 2018-08-16T18:49:45.070 回答
0

我同意这个答案,从长远来看,如果您计划对后端进行大量不同的网络调用,Retrofit 可能会更好。但是,如果您坚持在较低级别使用 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 {

    }
});
于 2018-08-16T18:59:24.867 回答