2013-08-25 11 views
1

我已经对几乎每个JSON httppost教程和StackOverflow问题进行了排序,并且认为我可能会疯了。有一次,我的Android应用程序完美地下拉数据并在提交JSONObject并接收JSONObject之后显示它。现在,在失去了一天的代码编码后,我无法再重新开始工作。Java SendHttpPost正在带回null JSONObject

我第一次使用this作为基础,它的工作,那么有人可以告诉我为什么我可能会在HttpClient.java中出现空错误?

更新:似乎现在工作,有点。但是收到的JSON应该看起来像this,而它包含的内容是{“mainSearchResult”:[]}。思考?

注意:是的,我确实有我的所有进口产品,并且可以找到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(); 
} 

}

+0

看起来你的心不是resultString一个有效的JSON对象,尝试打印出你resultString或调试应用程序,看看它的价值是什么。你也可以考虑在你的try catch外面加上你的resultString变量,如果你遇到一个错误,你可以打印出来。在你的try catch中添加一个JSONException,这样你可以缩小你的执行类型以进行调试。 –

+0

更新的附加信息 – mattcoker

+0

我不能告诉你,它与你从哪里获取数据的地方有关,你通过它传递什么参数等等......我想知道http调用是什么,并在浏览器中测试它,看看你是否可以从那里得到结果,并从这个角度对它进行处理。 –

回答

0

我用不同的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(); 
    } 

在此之后尝试打印响应(这是你的 “尝试捕捉” 范围):

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

除非我弄错了,那convertStreamToString方法正是我所用的字符。另外,我已经记录了convertSTreamToString的结果,当这样做,仍然得到{“mainSearchResult”的字符串:[]} – mattcoker

+0

是的,我现在看到它..Sorry 它可以是响应是空的吗?你可以显示你正试图解析的JSON吗? –

+0

要查看我想要拉下的JSON数据以及它应该如何显示,请参阅原始帖子中的更新。显然,他们有一些服务器问题,但现在,而不是实际的json数据,我收到构成错误页面的实际HTML,表示无法找到该文件(在其服务器上)。 – mattcoker

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

    }