为什么我对getInputStream()的调用返回一个空的html字符串?

时间:2017-07-17 00:14:44

标签: php android json post

想知道到底发生了什么,迫切需要帮助。

我试图从服务器返回一些JSON而不是... <!doctype html><html><head><meta charset="utf-8><title>Untitled Document</title></head><body></body></html>

所以...我的代码。

Android代码:

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()函数; ?&GT;

如果我在浏览器中输入URL,它会像我期望的那样回应tips.json的内容(在JSONLint上验证了这一点)。基本上,我不知道发生了什么。欢呼任何建议。

1 个答案:

答案 0 :(得分:0)

偶然发现了一个很棒的工具(PostMan,ttps://www.getpostman.com/),它大大简化了我的Java代码。它吐出以下代码......

                OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "showTips=test");
        Request request = new Request.Builder()
                .url("https://www.grinners4winners.com.au/grn1_app_backend/post2.php")
                .post(body)
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "a8529ea3-b9af-38ed-f9cc-322e3e9971e3")
                .build();

我所要做的就是按照以下方式加入响应。真的很简单。

        String returnvar = "";
        ResponseBody rb;
        try {
            Response response = client.newCall(request).execute();
            rb = response.body();
            returnvar = rb.string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return returnvar;