我已经对 StackOverflow 上的几乎所有 JSON httppost 教程和问题进行了分类,并且认为我可能会发疯。有一次,我的 Android 应用程序在提交 JSONObject 并接收到 JSONObject 后完美地拉取数据并显示它。现在,在失去一天的编码之后,我无法让它再次工作。
我第一次使用它作为基础,然后它就起作用了,所以有人可以告诉我为什么我可能会在 HttpClient.java 中出现空错误吗?
更新:似乎现在正在工作,有点。但是收到的 JSON 应该看起来像这样,而它包含的只是 {"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();
}
}