Async OkHttpClient Post

时间:2017-10-28 18:49:00

标签: android

Android和Java新手。需要帮助从MainActivity发送Post数据。据我所知,我必须使用异步,但它不会触发doinbackgroud。 另外我不知道try catch是否正确? 控制台日志记录仅显示" onPreExecute"

    public class PostHandler extends AsyncTask<String, Void, String> {
    String user, password;

    public PostHandler(String user, String password) {
        this.user = user;
        this.password = password;
        Log.e("AsyncTask", "onPreExecute");

    }

    @Override
    protected String doInBackground(String... params) {
        Log.v("AsyncTask", "doInBackground");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("user", user)
                .add("password", password)
                .build();

        Request request = new Request.Builder()
                .url("http://my.domain/register_01.php")
                .post(body)
                .build();

        try {
            Log.v("AsyncTask", "onPostExecute");
            client.newCall(request).execute();
        }
        catch (IOException e) {
            e.printStackTrace();
            Log.v("MyTag", "IOException " + e.toString());
        }
        return null;
    }
}

public void sendMessage(View view) {
    Log.i("MyTag", "Button pressed");
    String user = "Bengt";
    String password = "qaz";
    new PostHandler(user, password);
}

1 个答案:

答案 0 :(得分:1)

您没有执行AsyncTask,您需要调用execute(someString)方法。在您的情况下,您可以new PostHandler(user, password).execute(null)而不是最佳解决方案。如果您要使用AsyncTasks(这是相当弃用的BTW),我会通过execute方法将端点的url作为参数发送。

否则转移到Retrofit + RxJava或更现代的东西。