user3260939
user3260939

Reputation: 7

Async OkHttpClient Post

New to Android and Java. Need help with sending Post data from MainActivity. As i understand i have to use async, but it will not fire the doinbackgroud. Also i do not know if the try catch is correct? Console logging shows only "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);
}

Upvotes: 0

Views: 514

Answers (1)

4gus71n
4gus71n

Reputation: 4093

You are not executing the AsyncTask, yo need to call the execute(someString) method. In your case you could do new PostHandler(user, password).execute(null) not the best solution. If you're gonna use AsyncTasks (which is pretty deprecated BTW) I'd send the endpoint's url through the execute method as a parameter.

Otherwise move to Retrofit + RxJava or something more modern.

Upvotes: 1

Related Questions