【发布时间】:2018-02-04 01:48:10
【问题描述】:
代码请求 HTTP 连接到使用 php (phpMyAdmin) 运行的服务器。 它用 JSONObject 给出响应。
当我在亚洲进行测试时,它起作用了,但是它在美国给出了不同的响应。
使用给定的网址:
target = "http://example.com/request.php?value=DDPS"
这适用于网络浏览器,但在 Android 设备上它提供:
<html><body><script type="text/javascript" src="/cupid.js"></script><script>
.....path=/";location.href="http://example.com/request.php?value=DDPS
&ckattempt=1";</script></body></html>
这显然无法创建 JSONObject。
这种行为可能会出现什么问题?
我已设置允许从各大洲访问的服务器的权限。
这是我的 httpURL 连接代码:
try{
URL url = new URL(target);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setInstanceFollowRedirects(true);
InputStream inputstream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
String temp;
StringBuilder stringBuilder = new StringBuilder();
while((temp = bufferedReader.readLine()) != null)
{
stringBuilder.append(temp).append("\n");
}
bufferedReader.close();
inputstream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}catch (Exception e) {
e.printStackTrace();
}
编辑:
HttpURLConnection.setFollowRedirects(true);
给出相同的行为。
这是我的 php 代码,用于从数据库中获取数据并以 JSON 格式发送响应。 我应该在哪一点上实现 file_get_contents?
<?php
header("Content-Type: text/html; charset=UTF-8");
$con = mysqli_connect("localhost", "exampleID", "examplePW", "exampleID");
$value = $_GET["title"];
$result = mysqli_query($con, "SELECT * FROM DB WHERE title = '$value'");
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("item1"=>$row[1], "item2"=>$row[2], "item3"=>$row[3], "item4"=>$row[4]));
}
echo json_encode(array("response"=>$response), JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
【问题讨论】:
-
可能与服务器重定向有关。 Android 得到第一个响应。您可以使用 php scopt 和
file_get_contents方法验证它 -
不应 Content-Type 标头为
application/json吗?我没有看到任何重定向?这有什么关系? -
php 代码中没有重定向。您可以使用 Content-Type: text/html 创建 JSON,除非它们是正确的 JSON 格式。上面的代码完美地工作。我的问题是在托管服务器端。它阻止了从国外访问的所有 IP 地址。
标签: php android json mysqli httpurlconnection