我正在尝试通过HTTP POST请求的主体将数据(学生ID#)从Android应用程序发送到PHP文件。然后PHP文件将数据(现在只是一个字符串)发送回应用程序。但是,我的php似乎无法从请求中读取我的POST数据(学生ID#)。
我的.java文件:
JSONObject jsonParam = new JSONObject();
DataOutputStream printout;
String idIN = params[0];
jsonParam.put("id_in", idIN);
BufferedReader input;
String result;
URL url = null;
HttpURLConnection urlConnection = null;
url = new URL("http://10.0.2.2/project/connector.php");
urlConnection = (HttpURLConnection) url.openConnection();
//prepare request
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
printout = new DataOutputStream(urlConnection.getOutputStream ());
//printout.write(jsonParam);
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
//this returns: {"id_in":"1010101"}
Log.d("json out: ", jsonParam.toString());
printout.flush();
printout.close();
int response = -1;
response = urlConnection.getResponseCode();
input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
result = input.readLine();
// This returns 200
Log.d("response code: ", result);
urlConnection.disconnect();
我的.PHP文件:
<?php
header('Content-Type: text/html; charset=utf-8');
$id_in = "";
echo "test1";
$id_in = trim($_POST['id_in']);
echo "test2";
if (isset($_POST['id_in'])) {
echo "good";
}else{
echo "bad";
}
mysqli_close($myconn);
我的Android应用程序正在接收200响应代码并正在接收&#34; test1&#34;在响应中,但不是&#34; test2&#34;,所以当我的PHP文件尝试读取POST数据时必须出现问题:$id_in = trim($_POST['id_in']);
答案 0 :(得分:0)
不要忘记使用urlConnection.connect();