获取从Android到PHP的发布数据

时间:2015-09-26 04:06:28

标签: android cakephp cakephp-2.3

我有问题从Android接收帖子数据到CakePHP 2.3。以下是我的代码。此函数返回JSON对象形式的值。

public static JSONObject getJSONFromUrl(String url, JSONObject jObj) {

        // Making HTTP request
        InputStream is = null;
        try {
            // Default HTTP Client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            // HTTP POST Header

            HttpPost httpPost = new HttpPost(url);
            StringEntity se = new StringEntity(jObj.toString());
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            // Execute Http Post Request
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    /*
     * To convert the InputStream to String we use the
     * BufferedReader.readLine() method. We iterate until the BufferedReader
     * return null which means there's no more data to read. Each line will
     * appended to a StringBuilder and returned as String.
     */
        String json = "";
        try {
            // Getting Server Response
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            // Reading Server Response
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // Return JSON String
        Log.e("JSON Parser", jObj.toString());
        return jObj;
    }

我的CakePHP代码是:

function addBooksInDb() {
    $this->layout = false;
    $this->autoRender = false;
    debug($this->request);
    debug($_REQUEST['data']);
    debug($_POST);
    die();
}

此函数将在我的CakePHP REST API中获取来自Android POST的所有帖子详细信息。

0 个答案:

没有答案