【发布时间】:2014-04-01 16:39:47
【问题描述】:
我正在尝试使用最简单的代码从 Android 应用程序调用 Web API REST 方法,我发现 here 的代码看起来很有前途:
public String callWebService(String requestUrl)
{
String deviceId = "Android Device";
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(requestUrl);
request.addHeader("deviceId", deviceId);
ResponseHandler handler = new BasicResponseHandler();
String result = "";
try
{
result = httpclient.execute(request, handler); // <= a line too far
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
return result;
}
但是,它不会编译,告诉我:“不兼容的类型:对象无法转换为字符串”在这一行:
result = httpclient.execute(request, handler);
它确实提供了几个选项来试图规避僵局:
...但我不知道这些选项中的哪一个(如果有的话)是解决这个困境的首选方法。一种方式是“方式”吗?
更新
正如我所说,这段代码看起来很有希望,但我认为它基本上无法使用,因为它给了我可怕的“NetworkOnMainThreadException”来自 logcat:
04-01 13:18:41.861 1267-1267/hhs.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
. . .
java.lang.IllegalStateException: Could not execute method of the activity
. . .
Caused by: java.lang.reflect.InvocationTargetException
. . .
Caused by: android.os.NetworkOnMainThreadException
【问题讨论】:
标签: java android android-studio http-get android-gradle-plugin