我正在尝试获取 HTTP 响应。它在客户端不起作用。 尝试通过“ postman ”获得回复,并且成功了。
- 我确信 PHP 方面一切正常。
- 可能是因为类已被弃用。
Android 代码:`
//Connect to mysql.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("www.example.com/register.php");
//JSON object.
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", register_username);
jsonObject.put("password", register_password);
//Entity builder to send value.
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setText(jsonObject.toString());
httpPost.setEntity(entityBuilder.build());
//Getting response
HttpResponse response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
//When I try to print it out, I get value of "org.apache.http.message.BasicHttpResponse@32857430"`
PHP 代码:`
JSON EXAMPLE:
<?php
$con=mysqli_connect("localhost","tx","xxx","txxxt");
$data = json_decode(file_get_contents('php://input'));
$username = $data->{'username'};
$password = $data->{'password'};
$query = mysqli_query($con, "SELECT * FROM user WHERE username='$username'");
if(mysqli_num_rows($query) > 0){
$response = new stdClass();
$response->status="Already exists";
$response->code=0;
echo json_encode($response );}
else{
$response = new stdClass();
$response->status="Registered";
$response->code=1;
echo json_encode($response );
$sql_query = "insert into user values('$username','$password', 'null', 'null' ,'null');";
mysqli_query($con, $sql_query) or die (mysqli_error($con));
}
mysqli_close($con);
?>
`
如有任何帮助,我们将不胜感激!
最佳答案
我设法解决了这个问题:
WHAT I DID WRONG:
//JSON object.
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", register_username);
jsonObject.put("password", register_password);
//Entity builder to send value.
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setText(jsonObject.toString());
httpPost.setEntity(entityBuilder.build());
//Getting response
HttpResponse response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject responseObject = new JSONObject(responseBody);
WHAT I DID TO FIX
//JSON object.
JSONObject jsonObject = new JSONObject();
jsonObject.putOpt("username", register_username);
jsonObject.putOpt("password", register_password);
//Entity builder to send value.
EntityBuilder entityBuilder = EntityBuilder.create();
entityBuilder.setText(jsonObject.toString());
httpPost.setEntity(entityBuilder.build());
//Getting response
HttpResponse response = httpClient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject responseObject = new JSONObject(responseBody);
不知道为什么,但 putOpt 方法以某种方式修复了它。如果您知道原因,请随时回复。
关于java - 获取 http 响应 PHP 和 ANDROID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988373/