在Android中使用CakePHP Web服务并使用null响应

时间:2014-12-04 21:34:53

标签: android json cakephp

我遇到了大麻烦。

我正在制作一款Android应用程序,它使用了使用cakephp制作的本地Web服务。在本地,它的工作非常完美,但是现在,我将这些Web服务放在生产服务器中,当我从模拟器测试Android应用程序时,我的响应为空。

我的代码是:

      InputStream is = null;
  String result = "";

    ArrayList<NameValuePair> parameters= 
            new ArrayList<NameValuePair>();

parameters.add(new BasicNameValuePair("username", "hello"));

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(parameters));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null)
        {
           sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();    

我注意到参数在服务器上作为空内容到达

1 个答案:

答案 0 :(得分:0)

当我使用CakePHP服务时,此代码适用于我。 responseBody包含响应字符串,在我的例子中是JSON。

public static JSONObject httpPost(String url, List<NameValuePair> params) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = createHttpClient(); //new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    String responseBody = null;
    JSONObject jObject = null;
    try {
         httppost.setEntity(new UrlEncodedFormEntity(params));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        int responseCode = response.getStatusLine().getStatusCode();
        responseBody = EntityUtils.toString(response.getEntity());
        jObject = new JSONObject(responseBody);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    } catch (JSONException e) {
        // Oops
    }  catch (Exception e) {
    }
    return jObject;
}