I have a problem to receive post data from Android to CakePHP 2.3. Below is my code. This function returns values which are in JSON object form.
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;
}
And my CakePHP code is:
function addBooksInDb() {
$this->layout = false;
$this->autoRender = false;
debug($this->request);
debug($_REQUEST['data']);
debug($_POST);
die();
}
This function will get all post details that comes from an Android POST in my REST API of CakePHP.