2014-11-22 46 views
1

我使用這個JSON解析器試圖從Django的服務器JSON數據到Android,但得到HTML

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; 
    } 
} 

這是IM從Django的

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

返回JSON如何這是怎麼了我「M試圖讓它

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 
+0

請檢查您的日誌。您的回覆中可能沒有收到JSON字符串。 – AabidMulani 2014-11-22 19:15:40

+0

我認爲這是問題所在。但我不明白爲什麼。它在瀏覽器中返回JSON。 – madprops 2014-11-22 19:17:43

回答

0

首先響應: 響應是錯誤的。由於<!DOCTYPE主要與html數據。所以你的迴應有一些錯誤,或者服務器發送Html數據。

其次: 爲了得到JSON數據,你可以使用:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(URL_STRING); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity httpEntity = response.getEntity(); 
resultString = EntityUtils.toString(httpEntity); 
JSONObject jObj=new JSONObject(resultString); 
+0

我知道答案是錯誤的,這就是爲什麼我說我在標題中獲得HTML。您的解決方案可以獲取JSON數據,但我得到的是我在文章編輯部分中包含的相同HTML響應。 – madprops 2014-11-22 19:49:27

0

我想通了,這是一個非常愚蠢的問題。我不得不改變我的urls.py接受最後沒有斜槓的網址。另外我必須將@csrf_exempt裝飾器添加到該函數中才能使用。

1

TL; DR
httpPost.setHeader("Accept", "application/json");


HttpPost的默認的 「接受」 的HTTPHeader值爲 text/html, image/gif, image/jpeg, *; q=.2, /; q=.2

text/html使用django的返回JSON包裹着HTML。如果需要純JSON,Accept HttpHeader的值應該設置爲'application/json'

相關問題