Android asynchronus HTTP client problem - android

I am trying to implement asynchronus http client for Android and I am haveing a trouble with type mismatch:
The method execute(HttpUriRequest) in the type HttpClient is not applicable for the arguments (HttpRequest)
I am doing all based on this tutorial: http://blog.androgames.net/12/retrieving-data-asynchronously/
Have found a type in AsynchronousSender - private HttpRequest request; but I have still problem with above which occurs in:
public void run() {
try {
final HttpResponse response;
synchronized (httpClient) {
response = getClient().execute(request); //<-- here is that problem
}
// process response
wrapper.setResponse(response);
handler.post(wrapper);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can you suggest anything ?
cheers,
/Marcin

The code snippets on http://blog.androgames.net/12/retrieving-data-asynchronously/ are wrong. To fix it just replace HttpRequest with HttpUriRequest since the method signature is: HttpClient#execute(HttpUriRequest). It shouldn't be any problem since most requests you work with are HttpUriRequest instances.

Related

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed

Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed.
Below is my async task background code
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("URL");
String jsonresponse = "";
try {
StringEntity se = new StringEntity(gson.toJson(resultPojo).toString());
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPut);
HttpEntity httpEntity = response.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
System.out.println("res .... "+jsonresponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
serverside code :
#POST
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response submitUserResponse(#PathParam("userId") int userId,
#PathParam("id") int id, List<ResultPojo> responses) {
try {
//core logic goes here
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Alright just like what was discussed it is most likely a mismatch different HTTP methods, in this case A Put and a post, whenever you ever encounter that HTTP code(405) do perform a validation on the methods you used, it happens.405 errors often arise with the POST method. You may be trying to introduce some kind of input form on the Web site, but not all ISPs allow the POST method necessary to process the form.A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

android HTTP POST error

Ok so I created a method in a new class and called it from my activity in try catch block, and when I call it and pass my string value my issue appeared...
My issue started after executing the below method after:
HttpResponse httpresponse = httpclient.execute(httppostreq);
It went to the catch (IOException e) in my activity and when I tried to print the response string it gave me the a response from the server !!!!
So the issue is when I try to pass value to the POST it should return some data but it failed and it's returning the empty message from the server
Hint :
The empty message will appear if there were no values
jsonobj.put("screenType", requestString);
So did i passed the value or not ??? and why it's causing exception ??
public void postData(String requestString) throws JSONException, ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
JSONObject jsonobj = new JSONObject();
jsonobj.put("screenType", requestString);
//jsonobj.put("old_passw", "306");
HttpPost httppostreq = new HttpPost("mysite.org");
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
Log.i("in try", httpresponse.toString());
String responseText=null;
try {
responseText=EntityUtils.toString(httpresponse.getEntity());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.i("in Exception",e.toString());
Log.i("arse exception", httpresponse.toString());
}
}
i also added the internet permisssion
<uses-permission android:name="android.permission.INTERNET" />
You can't make network requests on the main thread. You'll get the error you are seeing now. You need to use either AsyncTask or you need to create a new thread. Personally, I'd use AsyncTask. When you use AsyncTask you can use the onPostExecute method to return the value to the main thread.
See : NetworkOnMainThreadException
As vincent said you can't execute network requests in the UI thread, it will give you a weird exception, but rather than using an AsyncTask which will be destroyed if your activity rotates as this Infographic shows, I can recommend you to use Robospice its the best network framework I have used and it's very easy to use, Good Luck.

AndroidHttpClient.execute is returning httpresponse as null [duplicate]

This question already has answers here:
How to connect to my http://localhost web server from Android Emulator
(17 answers)
Closed 9 years ago.
I am trying to access my uri from the below code
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object... params) {
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("");
HttpUriRequest uriGetRequest = new HttpGet("http://localhost:8080/restsql-0.8.6/res/");
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(uriGetRequest);
;
} catch (Exception e) {
// TODO Auto-generated catch block
if(e!=null){
Log.e("ModelLoader", e.getMessage(), e);
}
Log.e("Model Loader", "Error while calling execute");
}
return httpResponse;
}
};
asyncTask.execute(new Object());
But always the httpresponse is null. Even no exception is thrown.
I have checked with a valid uri like https://google.co.in/ and its working fine.
Also my URI from browser is working fine .
As there is no exception thrown I am not able to proceed further.
In AVD to connect to localhost you need to use url
http://10.0.2.2/
instead of
http://localhost/
For reference.
To access localhost in emulator use 10.0.2.2
http://localhost:8080/restsql-0.8.6/res/
should be
http://10.0.2.2:8080/restsql-0.8.6/res/
Check the docs

Android HttpCleint works on 2.2 but not on 4

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

How to use webview or open URL in AndEngine - Android

I'm utilizing a game engine called AndEngine (which I'm completely new to) in my Android app. I need to load a different URL from the application based on what position an onscreen joystick is in (uploading to a .cgi server). The dilemma is that I cannot open a URL connection! This may seem simple, but I've looked everywhere, tried multiple solutions and nothing's worked. In basic Android, I've always used a WebView (loadUrl() method), and it worked well. However, I have no idea to how to create a webview while also using AndEngine. My preference is that the connection did not show (loaded underneath the AndEngine scene?) because I will need the screen for other things. I've also tried other solutions. I just tried this code, but when I checked the server, nothing was opened:
#Override
public void onLoadResources() {
//methods n/a to this question
try {
URL url = new URL(setUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return scene; // AndEngine return statement
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
**I've tried using the HTTPConnection class before (without AndEngine) to open up a URL, but to no avail. So it may be that I was just doing something wrong here. Using AndEngine GLES2. If more info is needed, let me know (this is my first question on SO).
Also tried setting up my .xml layout on AndEngine using
#Override
protected int getLayoutID() {
return R.layout.main;
}
but it says: "The method getLayoutID() of type Control must override or implement a supertype method"
Edit in response to Nicolas Gramlich: Internet permissions were set and compiler was originally at 1.6. Still don't know what the issue is.
xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Set java compiler compliance to 1.6
I solved my issue. I had to run all network operations on a thread separate from the main one (else it will throw a NetworkOnMainThread exception). I don't know why nothing else worked, but this did the trick! Here I'm creating a new thread with the action I want to perform, and then starting it after exceptions are taken care of. I found my answer here
new Thread(new Runnable() {
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("your_url");
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

Categories

Resources