HTTP GET请求返回HTML?

5
我正在使用HTTP GET请求在安卓中加载数据。但是不知道为什么返回的是HTML而不是JSON结果。当在浏览器中加载时,相同的URL会得到JSON,但响应却是HTML。
我的HTTP GET调用格式如下...
url = new URL(urlString);

        //httpURLConnection = (HttpsURLConnection) url.openConnection();
        httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Connection", "keep-alive");

        httpURLConnection.setRequestProperty("Accept", "application/json"); // or application/jsonrequest
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        /*
        httpURLConnection.setRequestProperty("Content-Type",
                "application/json");*/
        httpURLConnection.setRequestProperty("UseCookieContainer", "True");
        httpURLConnection.setRequestProperty("Cookie", cokieValue);
        httpURLConnection.connect();

服务器如何决定发送哪种格式?您需要找出答案,然后相应地编写Android应用程序。 - Henry
3
似乎您遇到了404 HTML页面或其他错误。 - injecteer
不好意思,我的回复代码是200。只获取到HTML响应。 - Sankar
请在海报插件(网络浏览器)中检查此 Web 服务,然后在代码中进行测试。 - Krunal Indrodiya
请检查URL,确保返回结果。请返回JSON结果而不是ActionResult。 - sankar ganesh
3个回答

2

一旦您检查了服务器端代码... 在这之后,意味着要更改代码如下...

url = new URL(urlString);

        httpURLConnection = (HttpsURLConnection) url.openConnection();
        //httpURLConnection = (HttpURLConnection) url.openConnection();
    //  HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Connection", "keep-alive");
        httpURLConnection.setRequestProperty("Content-Type",
                "application/json");
        httpURLConnection.setRequestProperty("UseCookieContainer", "True");
        httpURLConnection.setChunkedStreamingMode(0);
        httpURLConnection.connect();

        if (httpURLConnection != null) {
            respCode = httpURLConnection.getResponseCode();
            messageStatus.setResponseCode(respCode);
        }
        if (respCode == 200) {
            InputStream responseStream = httpURLConnection.getInputStream();
            messageStatus.setResponseStream(responseStream);
        }

1
你是否掌控目标Web服务?
你是否尝试过使用"text/x-json"作为内容类型?最近我发现有些系统并不支持应用程序/json,即使它是标准格式。

1
服务器必须返回JSON而不是仅仅打印。例如,如果您使用PHP,请使用以下代码:
print(json_encode($response));

不是简单的打印方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接