I have a method (below) to get data from web services in my android program. It works fine with Android 2.2. But in 4.x it throws an exception with message “Error Requesting API”. Not sure which part is causing the exception in my code and why only in 4.x Can someone give me some pointers?
public static synchronized String performHTTPRequest(HttpUriRequest request)
throws ApiException, ParseException, IOException {
HttpClientWrapper cli=new HttpClientWrapper();
HttpClient client;
try {
client=cli.getClient();
HttpResponse response = client.execute(request);
// Check if server response is valid
StatusLine status = response.getStatusLine() ;
if (status.getStatusCode() != HTTP_STATUS_OK) {
throw new ApiException("Invalid response from server: " + status.toString());
}
return EntityUtils.toString(response.getEntity());
} catch (MalformedURLException e) {
throw new Error(e);
} catch (Exception cnrce) {
throw new ApiException("Error requesting API:");
}
}
In 4.0 or the verions above honeycomb you can not perform any http request on ui thread.
You need to perform these in asynctask.
EDIT:
Documentation
Code example for asynctask