如何使用Request body(application / json)和Request header进行API调用?

时间:2016-01-15 08:13:47

标签: android json api androidhttpclient

我是android的初学者。尝试使用Request body(application / json)和Request headers调用API。这是我试过的

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";
    }
}

它给出了错误,如

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

  

更新

尝试使用AsyncTask toast消息消息,但不显示on pre吐司消息显示其他人没有,也没有错误。有没有其他方法来调试它或我做错了?

这是代码

 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

    }

4 个答案:

答案 0 :(得分:1)

Android上的网络电话禁止在主线程上运行。

要解决此问题,只需在AsyncTask的doInBackground方法中运行代码即可。

这将确保您的代码在另一个线程上正常运行。 AsyncTask允许您灵活处理,在(onPreExecution)之前,(onProgressUpdate)之间,onPostExecute之后以及取消操作(onCancelled)时处理应用程序的状态。

请注意,只有doInBackground才能在另一个线程上运行。

答案 1 :(得分:1)

您正在主线程上执行此操作,当有人尝试在主线程上进行长时间工作时,会发生此异常,请尝试使用Async task

答案 2 :(得分:0)

此例外

android.os.NetworkOnMainThreadException
当应用程序尝试在主线程上执行网络操作时,会发生

。使用AsyncTask从中恢复。

有关详情,请参阅此link

希望这有帮助

答案 3 :(得分:0)

您正在主线程上执行一些长时间运行的操作。 请使用AsyncTaskHere是一个很好的教程。