I'm trying to use the simplest possible code for calling a Web API REST method from an Android app, and the code that I found here looked very promising:
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;
}
However, it won't compile, telling me: "incompatible types: Object cannot be converted to String" on this line:
result = httpclient.execute(request, handler);
It does give a couple of options in an attempt to circumvent the logjam:
...but I don't know which, if any, of these options is the preferred way to solve this dilemma. Is one way "the way"?
This code, as I said, looks promising to me, however I think it's basically unusable as is, because it gives me the dreaded "NetworkOnMainThreadException" From 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
Because you are using a raw type in
ResponseHandler handler = ...
With raw types, the type variables in the method declarations are erased. So everything appears as Object
(or whatever the leftmost bound of the type parameter is).
Instead, use a parameterized type
ResponseHandler<String> handler = ...
This also works because BasicResponseHandler
extends ResponseHandler<String>
.
Now
httpclient.execute(request, handler);
will have a return type associated with the type argument used when declaring handler
, which is String
and the result can therefore be assigned to a String
variable (or anywhere a String
is expected).
Try this:
result = httpclient.execute(request, handler).toString();
If i'm not wrong, you should be able to use the "toString" method to convert the return of execute method to String type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With