java - 试图从 Django 服务器获取 JSON 数据到 Android 但获取 HTML

标签 java android django

我正在使用这个 JSON 解析器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  // constructor
  public JSONParser() {
  }
  public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
      // defaultHttpClient
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      HttpResponse httpResponse = httpClient.execute(httpPost);
      HttpEntity httpEntity = httpResponse.getEntity();
      is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
          is, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "n");
      }
      is.close();
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
  }
}

这就是我从 Django 返回 JSON 的方式

return HttpResponse(json.dumps(data), content_type="application/json")

这就是我想要得到它的方式

JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);

这是错误

Error parsing data org.json.JSONException: Value n<!DOCTYPE of type java.lang.String cannot be converted to JSONObject

如果我在浏览器中访问该 URL,它会显示根据 JSON Lint 有效的 JSON。

编辑:这是我得到的回复

n<!DOCTYPE html>n<html lang="en">n<head>n  <meta http-equiv="content-type" content="text/html; charset=utf-8">n  <meta name="robots" content="NONE,NOARCHIVE">n  <title>RuntimeError at /get_json</title>n  <style type="text/css">n    html * { padding:0; margin:0; }n    body * { padding:10px 20px; }n    body * * { padding:0; }n    body { font:small sans-serif; }n    body>div { border-bottom:1px solid #ddd; }n    h1 { font-weight:normal; }n    h2 { margin-bottom:.8em; }n    h2 span { font-size:80%; color:#666; font-weight:normal; }n    h3 { margin:1em 0 .5em 0; }n    h4 { margin:0 0 .5em 0; font-weight: normal; }n    code, pre { font-size: 100%; white-space: pre-wrap; }n    table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }n    tbody td, tbody th { vertical-align:top; padding:2px 3px; }n    thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; }n    tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }n    table.vars { margin:5px 0 2px 40px; }n    table.vars td, table.req td { font-family:monospace; }n    table td.code { width:100%; }n    table td.code pre { overflow:hidden; }n    table.source th { color:#666; }n    table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }n    ul.traceback { list-style-type:none; color: #222; }n    ul.traceback li.frame { padding-bottom:1em; color:#666; }n    ul.traceback li.user { background-color:#e0e0e0; color:#000 }n    div.context { padding:10px 0; overflow:hidden; }n    div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }n    div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; }n    div.context ol li pre { display:inline; }n    div.context ol.context-line li { color:#505050; background-color:#dfdfdf; }n    div.context ol.context-line li span { position:absolute; right:32px; }n    .user div.context ol.context-line li { background-color:#bbb; color:#000; }n    .user div.context ol li { color:#666; }n    div.commands { margin-left: 40px; }n    div.commands a { color:#555; text-decoration:none; }n    .user div.commands a { color: black; }n    #summary { background: #ffc; }n    #summary h2 { font-weight: normal; color: #666; }n    #explanation { background:#eee; }n    #template, #template-not-exist { background:#f6f6f6; }n    #template-not-exist ul { margin: 0 0 0 20px; }n    #unicode-hint { background:#eee; }n    #traceback { background:#eee; }n    #requestinfo { background:#f6f6f6; padding-left:120px; }n    #summary table { border:none; background:transparent; }n    #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }n    #requestinfo h3 { margin-bottom:-1em; }n    .error { background: #ffc; }n    .specific { color:#cc3300; font-weight:bold; }n    h2 span.commands { font-size:.7em;}n    span.commands a:link {color:#5E5694;}n    pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; }n  </style>n  n  <script type="text/javascript">n  //<!--n    function getElementsByClassName(oElm, strTagName, strClassName){n        // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.comn        var arrElements = (strTagName == "*" && document.all)? document.all :n        oElm.getElementsByTagName(strTagName);n        var arrReturnElements = new Array();n        strClassName = strClassName.replace(/\-/g, "\-");n        var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");n        var oElement;n        for(var i=0; i<arrElements.length; i++){n            oElement = arrElements[i];n            if(oRegExp.test(oElement.className)){n                arrReturnElements.push(oElement);n            }n        }n        return (arrReturnElements)n    }n    function hideAll(elems) {n      for (var e = 0; e < elems.length; e++) {n        elems[e].style.display = 'none';n      }n    }n    window.onload = function() {n      hideAll(getEl

最佳答案

长话短说
httpPost.setHeader("Accept", "application/json");


HttpPost的默认“接受”HttpHeader 值是 text/html, image/gif, image/jpeg, *; q=.2,/; q=.2

当使用 text/html 时,django 返回用 HTML 包装的 JSON。如果需要纯 JSON,Accept HttpHeader 值应设置为 'application/json'

关于java - 试图从 Django 服务器获取 JSON 数据到 Android 但获取 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27081278/

相关文章:

java - 将投影形式 Hibernate HQL 查询映射到对象

java - 从应用程序代码中获取其他进程的 Hprof 转储

python - 删除Django中的部分url地址

python - 如何仅删除绘图顶部的空间 - matplotlib

python - django 可以延迟加载模型中的字段吗?

java - Spring <c :foreach issue jSTL java

java - 动态图形用户界面框架设计

android 出站来电显示 - 开/关

Android删除tabwidget中标签之间的空间

android - 如何避免在 android 的共享首选项中添加重复值?