Android JSON POST with OKHTTP
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()); } });
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.