这是php代码,我想在Android中使用HttpPost方法。我想检查与post方法一起发送的json对象是否与数据库中存在的数据匹配
if(!isset($_POST['data'])) {
echo "FAIL1";
return 'false';
}
$jsonObject = $_POST['data'];
$data = json_decode($jsonObject, true);
if(!is_array($data)) {
print_r($data);
exit;
echo "FAIL2";
return 'false';
}
$UNIQUE_ID = $data['UNIQUE_ID'];
$BAR_CODE = $data['BARCODE'];
$BATCH_CODE = $data['BATCHCODE'];
if(!isset($UNIQUE_ID) || trim($UNIQUE_ID) == '' || !isset($BAR_CODE) || trim($BAR_CODE) == '' || !isset($BATCH_CODE) || trim($BATCH_CODE) == '') {
echo "FAIL3";
return 'false';
}
$link = mysql_connect($db_server,$db_username,$db_pasword) or die("Can not connect to server $db_server.");
mysql_select_db("drugverifier",$link);
$query = "SELECT * FROM drugverifier where unique_id = $UNIQUE_ID AND bar_code = $BAR_CODE AND batch_code = $BATCH_CODE";
echo " TEST4";
$result = mysql_query($query,$link) or die("Can not able to run the query ' $query ' on server $db_server.");
echo "TEST5";
if(mysql_num_rows($result) > 0){
echo "SUCCESS6";
echo 'true';
}
else {
echo "FAILURE7";
echo 'false';
}
我的android代码是:
JSONObject j = new JSONObject();
try {
j.put("BARCODE", "8904017500190");
j.put("BATCHCODE", "220");
j.put("UNIQUE_ID", "9876");
} catch (JSONException e) {
Log.v("@@@@@JSONException", e.getMessage());
}
String url = "http://www.smartcloudinfotech.com/SmartDrugVerifier/verifyBarCode.php";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("data",j.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
response = httpclient.execute(httpPost);
Log.v("RESPONSE",""+response.toString());
Toast.makeText(this, "RESPONSE in doPOST()"+response.toString(), Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
Log.v("@@@@@@@@@@@@@@UnsupportedEncodingException", e.getMessage());
} catch (ClientProtocolException e) {
Log.v("@@@@@@@@@ClientProtocolException",e.getMessage());
} catch (IOException e) {
Log.v("@@@@@@@@@@IOException116", e.getMessage());
}
String temp = EntityUtils.toString(response.getEntity());
当我运行此程序时,变量temp的值不包含任何值。 请帮我解决我出错的地方。
答案 0 :(得分:0)
尝试使用BufferedReader
来阅读HttpEntity
的内容,如下所示:
void printResponse(HttpResponse response) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
修改强>
当我使用Curl向您的服务器发出POST data=test
时,我没有得到回复。我认为这是由于这段代码:
if(!is_array($data)) {
print_r($data);
exit;
echo "FAIL2";
return 'false';
}
首先,如果它不是数组,则要打印数组。这是没有意义的。 其次,退出,并回显你的“FAIL2”。
答案 1 :(得分:0)
您正在阅读Android中的错误响应,就像这样
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
此外,我不是一个伟大的PHP程序员,但我相信你正在读PHP中错误的值,你没有传递JSONArray据我所知,你传递的是JSONObject。 <\ n>删除
print_r($data);
exit;