我已经对几乎每个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();
}
}
看起来你的心不是resultString一个有效的JSON对象,尝试打印出你resultString或调试应用程序,看看它的价值是什么。你也可以考虑在你的try catch外面加上你的resultString变量,如果你遇到一个错误,你可以打印出来。在你的try catch中添加一个JSONException,这样你可以缩小你的执行类型以进行调试。 –
更新的附加信息 – mattcoker
我不能告诉你,它与你从哪里获取数据的地方有关,你通过它传递什么参数等等......我想知道http调用是什么,并在浏览器中测试它,看看你是否可以从那里得到结果,并从这个角度对它进行处理。 –