1

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

    }
undefined
  • 43
  • 1
  • 8
  • Put the api call code in Async class in `doInBackground()` method. Search on google for async class you will many example. Or use any third party library for the API Calls like `Volley` or `Retrofit` – Pankaj Jan 15 '16 at 08:17
  • oh thank you and above code is correct? – undefined Jan 15 '16 at 08:19

4 Answers4

1

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.

FrancescoC
  • 1,058
  • 10
  • 19
  • thanks will do , other than this my code is correct? – undefined Jan 15 '16 at 08:33
  • Checking your UPDATED code. Move every UI related code to "onPostExecute" method. onPostExecute runs after doInBackground and runs on main thread, where you can interact with your UI. Changes won't happen in doInBackground – FrancescoC Jan 15 '16 at 08:58
1

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.

Surabhi Singh
  • 803
  • 8
  • 14
0

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

vab
  • 723
  • 7
  • 15
0

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

silentsudo
  • 6,730
  • 6
  • 39
  • 81