我正在尝试从android向PHP文件发出请求。之后,我需要将PHP(单个代码)生成的响应保存到文件中,以便下次可以读取它而不必再次发出请求。对于请求,我创建了一个新方法,其内容如下:
> 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;
>
> }
我还修改了HttpHandler post()方法,以便可以获取代码并返回它,所以现在看起来像这样:
> 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();}
> }
目前,PHP的内容如下:
<?php $code = 12345; echo $code; ?>
嗯...问题是,我不知道为什么,但是我总是看到Toast好像没有收到任何代码(“您的代码是”),但是当我从资源管理器访问此PHP时,我总是得到我需要新的代码,因此无法将数据保存到文件中。
有什么建议么?在此先感谢大家
这是已解决问题的代码,希望对您有所帮助:
首先,用于在主要活动中调用异步的代码如下:
private String deviceIdHttpGetter(){
try
{
AsyncHttpDeviceId asyncId = new AsyncHttpDeviceId();
return asyncId.execute("http://www.cafegourmet.es/newUser.php").get();
}
catch(Exception e){
return e.toString();
}
}
}
最终,异步显示如下:
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;
}
}
希望有一天能对某人有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句