【问题标题】:Why is my call to getInputStream() returning an empty html string?为什么我对 getInputStream() 的调用返回一个空的 html 字符串?
【发布时间】: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手指会有所启发

标签: php android json post


【解决方案1】:

偶然发现了一个出色的工具(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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多