I am using HttpURLConnection to pass json query to php server and it doesn't work the way I want.
The connection is fine, I got proper error respond from server side and I am sure the json string is properly handled. eg:{"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}
However, the php server cannot load the variable $_POST with the string that I have sent. The code on android side is simple:
String temp_p = gson.toJson(diary);
URL url2 = new URL( "http://localhost:8080/****");
HttpURLConnection connection = (HttpURLConnection)url2.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes(temp_p);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println("respons:" + response.toString());
The code on php server looks like:
if (isset($_POST['id'])) {
$id = $_POST['id'];
..blablabla..
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing" ;
$response["_POST"] = $_POST ;
echo json_encode($response);
}
The $_POST is null in this case no matter what I sent ..
And after reaserching a bit, I found a solution that I have to modify the code on server side like the following:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
if (isset($request['id'])) {
$id = $request['id'];
Without touching the android code, the server can recieve and work on json data I sent now.
The problem is there is no way I can modify the code on the actual server.. So any idea why the $_POST not getting p
0 comments:
Post a Comment