【问题标题】:Java SendHttpPost is bringing back null JSONObjectJava SendHttpPost 正在带回 null JSONObject
【发布时间】:2013-08-25 21:20:12
【问题描述】:

我已经整理了 StackOverflow 上几乎所有 JSON httppost 教程和问题,我想我可能会发疯。有一次,我的 Android 应用程序在提交 JSONObject 并接收到 JSONObject 后完美地拉取数据并显示它。现在,在失去一天的编码之后,我无法让它再次工作。

我第一次使用this 作为基础,然后它就起作用了,所以有人可以告诉我为什么我可能会在 HttpClient.java 中得到空错误吗?

更新:似乎现在可以工作了,有点。但是收到的 JSON 应该看起来像 this,而它包含的只是 {"mainSearchResult":[]}。想法?

注意:是的,我确实有我所有的导入,并且可以在 here 找到 LogCat。我只用 Java 和 Android 编程了大约 3 周,所以请尽可能简单地解释清楚,希望不要依赖其他 StackOverflow 帖子来解释它,因为我向你保证,我已经阅读了它。

public class HttpClient {

public static final String TAG = HttpClient.class.getSimpleName();

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();

            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            instream.close();

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        } 

    }
    catch (Exception e)
    {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}


private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     * 
     * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

【问题讨论】:

  • 看起来您的 resultString 不是一个有效的 json 对象,尝试打印出您的 resultString 或调试您的应用程序以查看它的值是什么。您也可以考虑将 resultString 变量放在 try catch 之外,如果遇到错误,您可以将其打印出来。还要在 try catch 中添加 JSONException,以便缩小执行类型以进行调试。
  • 更新了更多信息
  • 我不能告诉你,这与你从哪里检索数据、传递它的参数等有关...我会说弄清楚 http 调用是什么并在浏览器,看看你是否可以从那里得到结果并从那个角度工作。

标签: java android json http-post


【解决方案1】:

我使用不同的 convertStreamToString 方法:

 private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

在此之后尝试打印响应(这在您的“Try Catch”范围内):

String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
Log.d("Reponse from request:",result); //Where you print to LogChat theresponse

然后我会尝试将字符串解析为 JSONObject

JSONObject jObject = new JSONObject(result);             
   if(result!=null)
   {
    //Here is where you do your thing....
   }

【讨论】:

  • 除非我弄错了,convertStreamToString 方法正是我使用的,一个字符一个字符。另外,我已经记录了 convertSTreamToString 的结果,这样做时,仍然得到 String of {"mainSearchResult":[]}
  • 是的,我现在看到了..对不起,回复是空的吗?你能显示你试图解析的 JSON 吗?
  • 要查看我尝试下拉的 JSON 数据以及它应该如何显示,请参阅原始帖子中的更新。显然他们有一些服务器问题,但现在我收到的不是实际的 json 数据,而是构成错误页面的实际 HTML,表明无法找到该文件(在他们的服务器上)。
【解决方案2】:
May this help you.

 // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        JsonArray jsonArray=json.getJSONArray("mainSearchResult");
String strAudio=jsonArray.getJSONObject(0).getString("AudioStr");//move the loop towards it upto jsonArray.length() and get all the string in the same manner

  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;

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多