Search code examples
androidjsonapiandroidhttpclient

How to do API call with Request body(application/json) and Request headers?


Im beginner of android. try to call API with Request body(application/json) and Request headers.here is what i have tried

private String doEmotionAPICall(String imgURL){

        //creating map object to creat Json object from it
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("https://api.projectoxford.ai/emotion/v1.0/recognize");
            JSONObject data = new JSONObject();
            try {
                data.put("url", imgURL);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            StringEntity se = new StringEntity(data.toString());

            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");

            post.setEntity(se);
            post.setHeader("Ocp-Apim-Subscription-Key", "my key");
            HttpResponse response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity());

            Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "result if success";
    }
}

it gives error like

01-15 13:13:36.188    3849-3849/net.simplifiedcoding.imageuploadsample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: net.simplifiedcoding.imageuploadsample, PID: 3849
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:374)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:575)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:498)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:476)
            at net.simplifiedcoding.imageuploadsample.MainActivity.doEmotionAPICall(MainActivity.java:184)
            at net.simplifiedcoding.imageuploadsample.MainActivity.onClick(MainActivity.java:149)
            at android.view.View.performClick(View.java:4456)
            at android.view.View$PerformClick.run(View.java:18465)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/563b31ea778daf121cc3a5fa

UPDATE

tried with AsyncTask toast message message not showing only on pre toast message shows others are not and no errors also. is there any other way to debug it or im doing wrong?

here is code

 private  void doEmotionAPICall() {

        class CallAPI extends AsyncTask<String, Integer, String> {
            protected void onPreExecute() {
                Toast.makeText(getApplicationContext(), "on pre", Toast.LENGTH_LONG).show();
            }
            protected void onPostExecute() {
                Toast.makeText(getApplicationContext(), "on post", Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(String... params) {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost("https://api.projectoxford.ai/emotion/v1.0/recognize");
                    JSONObject data = new JSONObject();
                    String imgURL = "http://amysdayspa.com/wp-content/uploads/2015/02/smile.jpg";
                    try {
                        data.put("url", imgURL);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getApplicationContext(), "json" + data, Toast.LENGTH_LONG).show();

                    StringEntity se = new StringEntity(data.toString());

                    se.setContentEncoding("UTF-8");
                    se.setContentType("application/json");
                    post.setEntity(se);
                    post.setHeader("Ocp-Apim-Subscription-Key", "my key");
                    HttpResponse response = client.execute(post);
                    Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_LONG).show();

                    String result = EntityUtils.toString(response.getEntity());

                    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                return "selva";
            }
        }
        String imgURL = "http://amysdayspa.com/wp-content/uploads/2015/02/smile.jpg";
        new CallAPI().execute(imgURL);

        //creating map object to creat Json object from it

    }

Solution

  • You are doing some long running operation on Main Thread. Please use AsyncTask. Here is a good tutorial for this.