从PHP获取响应并保存在文件android中


get response from php and save in a file android

我试图从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; ?>

嗯…问题是,我不知道为什么,但我总是看到吐司好像没有收到代码("你的代码是"),但是当我从资源管理器访问这个PHP时,我总是得到我需要的新代码,因此我不能将数据保存到文件。

有什么建议吗?提前感谢大家

下面是解决问题的代码,希望对大家有所帮助:

首先,在主活动中调用async的代码如下所示:
private String deviceIdHttpGetter(){
        try
        {
        AsyncHttpDeviceId asyncId = new AsyncHttpDeviceId();
        return asyncId.execute("http://www.cafegourmet.es/newUser.php").get();
        }
        catch(Exception e){
            return e.toString();
        }
    }
}

Async最后的读取如下:

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;
      }
}

希望有一天能帮到别人。