我正在尝试使用最简单的代码来从Android应用程序调用Web API REST方法,而我找到的代码在这里看起来非常有前途:
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;
}
然而,它无法编译,告诉我:“不兼容的类型:无法将Object转换为String”,出现在这一行:
result = httpclient.execute(request, handler);
它提供了一些选项来尝试规避僵局:
![enter image description here](https://istack.dev59.com/pn9gx.webp)
更新:
正如我所说,这段代码看起来很有前途,但我认为它基本上无法使用,因为它会给我带来可怕的“NetworkOnMainThreadException”异常。从日志中可以看到:
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