undefined
undefined

Reputation: 43

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

    }

Upvotes: 1

Views: 4550

Answers (4)

Surabhi Singh
Surabhi Singh

Reputation: 803

You are doing it on main thread, this exception occurred when someone tries to do long work on main thread, try to use Async task.

Upvotes: 1

FrancescoC
FrancescoC

Reputation: 1058

Network calls on Android are forbidden to run on main thread.

To solve this, simply run your code in an AsyncTask's doInBackground method.

This will ensure your code will be run properly on another thread. AsyncTask allows you much flexibility, handling the state of the app before(onPreExecution) , during (onProgressUpdate), after(onPostExecute), and in case of cancel of operation (onCancelled) .

Be aware, ONLY doInBackground will run on another thread.

Upvotes: 1

silentsudo
silentsudo

Reputation: 6973

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

Upvotes: 0

vab
vab

Reputation: 723

This exception

android.os.NetworkOnMainThreadException

occurs when the application attempts to do a network operation on the main thread. Use AsyncTask to recover from this.

For more information please go through this link

Hope this helps

Upvotes: 0

Related Questions