【问题标题】:My json is appearing as a HTML when parsed (android)解析时,我的 json 显示为 HTML(android)
【发布时间】:2015-06-16 08:00:30
【问题描述】:

我正在尝试使用JSON 格式从URL 解析和获取值。 URL在浏览器中使用时JSON的格式如下:

{"CompanyID":"1","Message":"Not active user","Success":"false","UserID":"2"}

我的JsonParser代码如下所示:

import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
* Created by Fathi on 6/16/2015.
*/
public class JsonParser {
final String TAG = "JsonParser.java";

static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArray = null;
static String result = "";

public JSONArray getJSONFromUrl(String url) {

    // make HTTP request
    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpget);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        Log.e(TAG, "JSON status code:  " + statusCode);

        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();
        result = sb.toString();
        Log.e(TAG, "JSON string:  " + result);

    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {           
        jArray = new JSONArray(result);

    } catch (JSONException e) {
        Log.e(TAG, "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;
}

}

我在活动中使用的代码如下:

    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    final String TAG = "AsyncTaskParseJson.java";

    // set your json string url here
    String yourJsonStringUrl = "**MY URL COMES HERE**";

    // contacts JSONArray
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... arg0) {



        try {

            // instantiate our json parser
            JsonParser jParser = new JsonParser();

            // get json string from url

            JSONArray jsonArray = jParser.getJSONFromUrl(yourJsonStringUrl);


            // loop through all users
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject c = jsonArray.getJSONObject(i);

                // Storing each json item in variable
                String Success = c.getString("Success");


                // show the values in our logcat
                Log.e(TAG, "Success: " + Success);


            } } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {}

我的 Logcat 给了我以下错误(我有 HTTP 响应和字符串):

06-16 03:50:10.841    2470-2489/iss.voltappinterface E/JsonParser.java﹕ JSON     status code:  200
06-16 03:50:10.911    2470-2489/iss.voltappinterface E/JsonParser.java﹕ JSON string:  <html><head><title>Object moved</title></head><body>n<h2>Object moved to <a href="/voln
06-16 03:50:10.921    2470-2489/iss.voltappinterface E/JsonParser.java﹕ Error parsing data org.json.JSONException: Value <html><head><title>Object of type java.lang.String cannot be converted to JSONObject

我可以看到我的JSON 出于某种原因被处理为HTML,这是我不明白的,因为它在浏览器中看起来很完美。任何帮助将不胜感激。

【问题讨论】:

  • 检查您的服务器端点是否向您发送 Html 内容作为响应。
  • 就像 Nullbyte 所说:你根本没有收到任何 JSON,因为你似乎调用了错误的地址。服务器告诉您,您尝试拨打的电话已移动。
  • @NullByte 感谢大家的快速响应,很抱歉,电话是如何移动的,如果您有任何想法,URL 在本地公司服务器上,我不确定如何它可以简单地“移动”。再次感谢
  • @TimothyGroote 你也一样 :)
  • @FathiEid 我不知道。也许与服务器的管理员核实。我也看不到它现在在哪里,因为回复在moved to &lt;a href="/voln

标签: android html json android-json


【解决方案1】:

查看端点上的 content-type 标头,它可能是 text/html 并且 应该是 application/json

编辑:正如@Fathi Eid 建议的那样,您可以强制使用内容类型:

httpget.setHeader("Content-Type", "application/json");
httpget.setHeader("Accept", "application/json");

请注意,这是一个修复,您应该真正考虑在 api 服务器上而不是在客户端上更改响应内容类型。

【讨论】:

  • 服务器有Microsoft Visual Studio,它包含API的所有信息等,我检查了“endpoint”并在web.config中找到它,但它没有“content-type” .我对服务器不是很有经验,因为我没有制作 API,我只是想连接到它。我找对地方了吗?
  • 您可以尝试在 Chrome 上使用 Postman 扩展程序,并在“标题”选项卡上查看内容类型。如果你不能改变它或者没有找到怎么做,也许 SO 或 ServerFault 是正确的地方
  • 不知道我的 chrome 出了什么问题,每次尝试下载扩展都会出错,我会尽快尝试
  • 感谢您为我指明正确的方向,最终使用了这些:httpget.setHeader("Content-Type", "application/json"); httpget.setHeader("接受", "application/json");
  • 我已将@FathiEid 修复添加到答案中,因为它是相关的。
猜你喜欢
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多