【发布时间】:2017-07-17 00:14:44
【问题描述】:
想知道到底发生了什么,迫切需要帮助。
我正在尝试从服务器返回一些 JSON 并取而代之...
<!doctype html><html><head><meta charset="utf-8><title>Untitled Document</title></head><body></body></html>
所以...我的代码。
安卓代码:
JSONObject data = new JSONObject();
try {
data.put("showTips", "true");
} catch (JSONException e) {
e.printStackTrace();
}
// Headers
ArrayList<String[]> headers = new ArrayList<>();
headers.add(new String[]{"custom-header", "custom value"});
headers.add(new String[]{"Content-Type", "application/json"});
try{
URL url = new URL("https://www.grinners4winners.com.au/grin1_app_backend/post2.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
for (int i = 0; i < headers.size(); i++) {
conn.setRequestProperty(headers.get(i)[0], headers.get(i)[1]);
}
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setUseCaches(false);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(data));
writer.flush();
writer.close();
os.close();
conn.connect();
int responseCode=conn.getResponseCode();
String responseMessage=conn.getResponseMessage();
JSONObject jsonObject = new JSONObject();
jsonObject.put("status_code", responseCode);
jsonObject.put("status_message", responseMessage);
if (jsonObject.getInt("status_code")< 400) {
// BufferedReader in = new BufferedReader(new InputStreamReader(httpResult.getResponse()));
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = "";
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
in.close();
return result;
}else{
return "false: ".concat(String.valueOf(responseCode));
}
} catch (Exception e) {
return "Exception: ".concat(e.getMessage());
}
出于测试目的,我已经厌倦了将 PHP 缩减为基本必需品,删除了一堆其他代码和额外的 $_POST 检查,但仍然没有运气。 这是PHP
<?php
ob_start();
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json;charset=utf-8');
header ('Cache-Control: no-cache, must-revalidate');
header("Expires: Sun, 16 Jul 2017 05:00:00 GMT");
//if ($_POST['showTips']){
$json = json_encode(file_get_contents('./tips.json'));
if ($json===false){
$json = json_encode(array("jsonError",json_last_error_msg()));
if ($json ===false){
$json='{"jsonError":"unknown"}';
}
http_response_code(500);
}
echo $json;
//}
ob_end_flush(); ?>
如果我在浏览器中输入 URL,它会像我预期的那样回显tips.json 的内容(在 JSONLint 上验证了这一点)。基本上,我不知道发生了什么。为任何建议干杯。
【问题讨论】:
-
"如果我在浏览器中输入 URL" -- 如果您的意思是通过地址栏,那将导致 GET 请求,而不是 POST。
-
没错,只是包含它以表明它在检索文件时没有遇到任何问题。那么..为什么不能用 POST 做到这一点?
-
仍然没有进展,明天x手指会有所启发