我使用cakephp开发了一个api,现在我正在尝试在android上实现POST和GET功能。 GET工作正常但是当我发布数据时,它被添加到数据库但json响应不起作用!这是我发布数据时得到的结果: error message
这是我的android代码:
public class TaskManager {
public static class AddLocation extends AsyncTask<String, Void, String> {
String result ;
@Override
protected String doInBackground(String... params) {
String addWaypointUrl = "http://xxx.xxx.xxx.xxx:xxxx/locations/addlocation";
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIsImV4cCI6MTUwMjI0MDc5NX0.3gRtjvVuMPJKJwvkzPcjK19zqJadCUiT2LH-Ut4TVgk";
URL object = null;
try {
object = new URL(addWaypointUrl);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", token);
con.setRequestMethod("POST");
JSONObject cred = new JSONObject();
cred.put("id_user","12");
cred.put("name","doci vida");
cred.put("street","rue de paris");
cred.put("description","restaurant italien");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(cred.toString());
wr.flush();
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
// JSONObject jObj = new JSONObject(sb.toString());
Log.e("result","f"+sb.toString());
if (sb.toString() != null) {
return sb.toString();
}
} else {
System.out.println(con.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
Log.e("result","null "+result);
}
}
}
我在发布问题之前在互联网上搜索了很多,但我无法解决这个问题。任何想法?
更新 这是我的PHP代码:
public function addLocation()
{
$location = $this->Locations->newEntity();
if ($this->request->is('post')) {
$location = $this->Locations->patchEntity($location, $this->request->data);
if ($this->Locations->save($location)) {
$this->set([
'success' => 1,
'_serialize' => ['success']
]);
} else {
$this->set([
'success' => 0,
'errors' => $location->errors(),
'_serialize' => ['success','errors']
]);
}
}
}