解析Json Data时遇到麻烦

时间:2014-09-02 10:43:19

标签: android json android-json

我正在尝试解析JSON并获取数据当我尝试获取数据时结果似乎是xml文档,但在JSONLint和postman中它看起来很好

我正在使用的代码是......

private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*mProgressDialog = new ProgressDialog(this,R.style.CustomDialog);*/

         mProgressDialog = new ProgressDialog(getActivity(),R.style.MyTheme);
         mProgressDialog.setCancelable(false);
         mProgressDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
         mProgressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {

         HttpParams params1 = new BasicHttpParams();
         HttpProtocolParams.setVersion(params1, HttpVersion.HTTP_1_1);
         HttpProtocolParams.setContentCharset(params1, "UTF-8");
         params1.setBooleanParameter("http.protocol.expect-continue", false);
         HttpClient httpclient = new DefaultHttpClient(params1);

         HttpPost httppost = new HttpPost("");
         try{
          HttpResponse http_response= httpclient.execute(httppost);

          HttpEntity entity = http_response.getEntity();
          String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
          Log.i("Response", jsonText);
            jsonobject = new JSONObject(jsonText); 

          }catch(Exception e){

          }




        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        mProgressDialog.dismiss();
    }
}

我得到的回应是

          09-02 16:03:03.556: I/Response(4575): ?<?xml version="1.0" encoding="utf-8"?>

             09-02 16:03:03.556: I/Response(4575): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0               Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    09-02 16:03:03.556: I/Response(4575): <html xmlns="http://www.w3.org/1999/xhtml">

      09-02 16:03:03.556: I/Response(4575):   <head>

      09-02 16:03:03.556: I/Response(4575):     <title>Service</title>

      09-02 16:03:03.556: I/Response(4575):     <style>BODY { color: #000000; background-color:         white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-   size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration:   underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active {   color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; f ont-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>

     09-02 16:03:03.556: I/Response(4575):   </head>

     09-02 16:03:03.556: I/Response(4575):   <body>

       09-02 16:03:03.556: I/Response(4575):     <div id="content">

      09-02 16:03:03.556: I/Response(4575):       <p class="heading1">Service</p>

      09-02 16:03:03.556: I/Response(4575):       <p xmlns="">Method not allowed. 

Please see the       <a rel="help-page" href="http://com/API.svc/help">service help page</a> for    constructing valid requests to the service.</p>

09-02 16:03:03.556: I/Response(4575):     </div>

09-02 16:03:03.556: I/Response(4575):   </body>

09-02 16:03:03.556: I/Response(4575): </html>

IOS上的一切正常,解析结果非常完美。我也尝试了其他一些方法,但反应是一样的, 如果有人帮我解决这个问题,那将会很棒

2 个答案:

答案 0 :(得分:1)

您的响应实际上是一条XML错误消息,抱怨使用过的HTTP方法POST。您提供的链接在浏览器中工作正常,因此将HttpPost替换为HttpGet应该有效。

顺便说一下,不建议从Android 2.3开始使用Apache框架。对于更高版本,您应该使用HttpUrlConnection或切换到其中一个库:RetrofitVolley,它们将为您处理。

答案 1 :(得分:0)

创建此类JSONParser.java:

public class JSONParser {

    static String url;

    static InputStream is;
    static String result;
    static JSONObject jsonObject;

    static HttpClient httpClient;
    static HttpPost httpPost;

    static List<NameValuePair> pairs;

    static HttpResponse response;
    static HttpEntity entity;

    private static void init() {
        // TODO Auto-generated constructor stub
        is = null;
        result = "";
        jsonObject = new JSONObject();
        httpPost = null;
        httpClient = new DefaultHttpClient();
    }

    public static String getResult(InputStream is)  {
        // TODO Auto-generated method stub
        BufferedReader reader;
        StringBuilder stringBuilder = null;

        try {
            reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);

            stringBuilder = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            is.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stringBuilder.toString();    
    }

    public static JSONObject getJSONData() {
        // TODO Auto-generated method stub
        try{
            init();

            url = "http://almithaq.mawaqaademo11.com/API.svc/getAlbumPhotosList";

            httpPost = new HttpPost(url.toString());

            response = httpClient.execute(httpPost);

            entity = response.getEntity();

            is = entity.getContent();

            /* Convert response to string */
            result = getResult(is);

            jsonObject = new JSONObject(result);

        }catch(ClientProtocolException e){
            Log.e(TAG, "Error in Client Protocol : "+e.toString());
        }catch(JSONException e){
            Log.e(TAG, "Error Parsing data "+e.toString());
        }catch(Exception e){
            Log.e(TAG, "Error in HTTP Connection : "+e.toString());
        }
        return jsonObject;
    }
}

并获得JSON使用:

JSONParser.getJSONData();
doInBackground()

中的

可能会有用......

如果有任何问题请问我...