Reputation: 33
I'm trying to make a request from android to a PHP file. After that, i need to save the response generated by the PHP (a single code) into a file so i can read it next times without having to make the request again. For the request, i created a new method which reads as follows:
> private String deviceIdHttpGetter(){
> HttpHandler handler = new HttpHandler();
> String code=handler.post("http://www.cafegourmet.es/newUser.php");
> Toast.makeText(getApplicationContext(), "your code is " + code, Toast.LENGTH_SHORT).show();
> return code;
>
> }
I also moddified the HttpHandler post() method so i can get the code and return it, so now it looks like this:
> public String post(String postURL){
> try {
> HttpClient client = new DefaultHttpClient();
> HttpPost post = new HttpPost(postURL);
> HttpResponse response = client.execute(post);
> HttpEntity ent = response.getEntity();
> String text = EntityUtils.toString(ent);
> return text;
> }
>
> catch(Exception e) { return e.getMessage();}
> }
The PHP, right now, reads as follows:
<?php $code = 12345; echo $code; ?>
Well... the problem is that, I don't know why, but I ALWAYS see the Toast as if no code were recieved ("your code is "), but when I access this PHP from the explorer, I always get the new code I need, therefore i cannot save the data to a file.
Any suggestions? Thanks in advance to everyone
Upvotes: 1
Views: 1953
Reputation: 33
Here's the code with the problem solved, hope it helps someone:
First, the code for calling the async in the main activity reads as following:
private String deviceIdHttpGetter(){
try
{
AsyncHttpDeviceId asyncId = new AsyncHttpDeviceId();
return asyncId.execute("http://www.cafegourmet.es/newUser.php").get();
}
catch(Exception e){
return e.toString();
}
}
}
And the Async finally reads as following:
public class AsyncHttpDeviceId extends AsyncTask<String, Integer, String> {
String code="";
public AsyncHttpDeviceId () {
}
/**
* background
*/
protected String doInBackground(String... posturl ) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(posturl[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
return e.toString();
} catch (IOException e) {
return e.getMessage();
}
return responseString;
}
protected void onPostExecute(String result) {
code=result;
}
}
Hope this helps someone someday.
Upvotes: 1