B. *_*non 5 java android http-get android-studio android-gradle-plugin
我正在尝试使用最简单的代码从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;
}
Run Code Online (Sandbox Code Playgroud)
但是,它不会编译,告诉我:"不兼容的类型:对象不能转换为String"在这一行:
result = httpclient.execute(request, handler);
Run Code Online (Sandbox Code Playgroud)
它确实提供了几个选项来试图绕过logjam:

......但我不知道哪些选项(如果有的话)是解决这一难题的首选方式.一种方式"方式"?
正如我所说,这段代码看起来很有希望,但我觉得它基本上不可用,因为它给了我可怕的" 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
Run Code Online (Sandbox Code Playgroud)
因为您使用的是原始类型
ResponseHandler handler = ...
Run Code Online (Sandbox Code Playgroud)
对于原始类型,方法声明中的类型变量将被删除.所以一切都显示为Object(或类型参数的最左边界限).
而是使用参数化类型
ResponseHandler<String> handler = ...
Run Code Online (Sandbox Code Playgroud)
这也有效,因为BasicResponseHandler扩展ResponseHandler<String>.
现在
httpclient.execute(request, handler);
Run Code Online (Sandbox Code Playgroud)
将具有与声明时使用的类型参数关联的返回类型handler,String因此可以将结果分配给String变量(或任何String预期的位置).
| 归档时间: |
|
| 查看次数: |
20939 次 |
| 最近记录: |