如何使用 Request body(application/json) 和 Request headers 进行 API 调用?
How to do API call with Request body(application/json) and Request headers?
我是 android 的初学者。尝试使用请求正文 (application/json) 调用 API 并且请求 headers.here 是我尝试过的
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)
UPDATE
尝试使用 AsyncTask
toast 消息消息不显示,仅 on pre
toast 消息显示其他人不显示,也没有错误。有没有其他方法可以调试它或者我做错了?
这是代码
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
}
这个异常
android.os.NetworkOnMainThreadException
当应用程序试图在主线程上执行网络操作时发生。使用 AsyncTask 从中恢复。
有关详细信息,请阅读此 link
希望对您有所帮助
Android 上的网络调用被禁止在主线程上 运行。
要解决这个问题,只需 运行 您在 AsyncTask 的 doInBackground 方法中的代码。
这将确保您的代码在另一个线程上 运行 正确。 AsyncTask 允许您非常灵活地处理应用程序在(onPreExecution)之前、期间(onProgressUpdate)、之后(onPostExecute)以及在操作取消时的状态(onCancelled)。
请注意,只有 doInBackground 会在另一个线程上 运行。
您正在主线程上执行此操作,当有人试图在主线程上执行长时间工作时会出现此异常,请尝试使用 Async task。
我是 android 的初学者。尝试使用请求正文 (application/json) 调用 API 并且请求 headers.here 是我尝试过的
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)
UPDATE
尝试使用 AsyncTask
toast 消息消息不显示,仅 on pre
toast 消息显示其他人不显示,也没有错误。有没有其他方法可以调试它或者我做错了?
这是代码
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
}
这个异常
android.os.NetworkOnMainThreadException
当应用程序试图在主线程上执行网络操作时发生。使用 AsyncTask 从中恢复。
有关详细信息,请阅读此 link
希望对您有所帮助
Android 上的网络调用被禁止在主线程上 运行。
要解决这个问题,只需 运行 您在 AsyncTask 的 doInBackground 方法中的代码。
这将确保您的代码在另一个线程上 运行 正确。 AsyncTask 允许您非常灵活地处理应用程序在(onPreExecution)之前、期间(onProgressUpdate)、之后(onPostExecute)以及在操作取消时的状态(onCancelled)。
请注意,只有 doInBackground 会在另一个线程上 运行。
您正在主线程上执行此操作,当有人试图在主线程上执行长时间工作时会出现此异常,请尝试使用 Async task。