Andy
Andy

Reputation: 129

Android JSON POST with OKHTTP

I´m looking for a solution to implement a JSON-POST request with OKHTTP. I´ve got an HTTP-Client.java file which handles all the methods (POST, GET, PUT, DELETE) and in the RegisterActivity I´d like to POST the user-data (from the input fields) JSON-formatted to the server.

This is my HTTP-Client.java

    public class HttpClient{

        public static final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        public static OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        public static Call post(String url, String json, Callback callback) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);

            Request request = new Request.Builder()
                    .url(url)
                    .post(body.create(JSON, json))
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callback);
            return call;
        }
}

... and this is the onClick-Part from the RegisterActivity

btnRegRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO

                String registerData = "{\"email\":\"" + etRegisterEmail.getText().toString() + "\",\"password\":\"" + etRegisterPasswort.getText().toString() + "\"}";


                try {
                    HttpClient.post(ABSOLUTE_URL, registerData, new Callback(){
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }
                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                String resp = response.body().string();
                                if (resp != null) {
                                    Log.d("Statuscode", String.valueOf(response.code()));
                                    Log.d("Body", response.body().string());
                                }
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

Everytime I start the app it crashes when I click the Register-Button caused by a FATAL EXPECTION 'android.os.NetworkOnMainThreadException'

I´ve alread read something about the AsyncTask but I don´t know exactly how to do this.

Upvotes: 2

Views: 11276

Answers (3)

Rahul Deep Singh
Rahul Deep Singh

Reputation: 190

Try using Retrofit library for making Post request to the server. This provides a fast and reliable connection to the server.
You can also use Volley library for the same.

Upvotes: 0

Moktahid Al Faisal
Moktahid Al Faisal

Reputation: 910

Try my code below

  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Map<String, String> params = new HashMap<String, String>();
        params.put("msisdn", "123123");
       params.put("name", "your name");
        JSONObject parameter = new JSONObject(param);
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON, parameter.toString());
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json; charset=utf-8")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("response", call.request().body().toString());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                  Log.e("response", response.body().string());
            }


    });

Upvotes: 4

josemgu91
josemgu91

Reputation: 719

It's because you are trying to execute the HTTP query on the main thread (or UI thread). You shouldn't do a long task on the main thread because your app will hang, because the drawing routines are executed in that thread (hence his another name "UI Thread"). You should use another thread to make your request. For example:

new Thread(){
       //Call your post method here. 
    }.start();

The Android asynctask is a simple class to do asynchronous work. It executes first his "onPreExecute" method on the calling thread, then his "doInBackground" method on a background thread, then his "onPostExecute" method back in the calling thread.

Upvotes: 0

Related Questions