【发布时间】:2015-11-04 12:31:24
【问题描述】:
我正在使用 HttpURLConnection 将 json 查询传递给 php 服务器,但它不能按我想要的方式工作。
连接很好,我从服务器端得到了正确的错误响应,我确信 json 字符串得到了正确处理。例如:
{"id":55,"date":"2011111","text":"","latitude":13.0,"longitude":123.0,"share":0,"image":"Image","sound":"sound"}
但是,php 服务器无法使用我发送的字符串加载变量 $_POST。 android端的代码很简单:
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());
php服务器上的代码如下:
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);
}
在这种情况下,无论我发送什么,$_POST 都是 null ..
经过一番研究,我找到了一个解决方案,我必须修改服务器端的代码,如下所示:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
if (isset($request['id'])) {
$id = $request['id'];
无需接触android代码,服务器就可以接收并处理我现在发送的json数据。
问题是我无法修改实际服务器上的代码。所以知道为什么 $_POST 没有得到 p
【问题讨论】:
标签: php android json httpurlconnection