我正在尝试与我的网络服务器交换数据。我遇到问题的代码是:
public void getOnlineData(View view) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
int TIMEOUT_MILLISEC = 10000;
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient();
String url = "http://twenty5eight.co.uk/portal/" +
"json/json.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("id", jObject.getString("id"));
map.put("name", jObject.getString("name"));
map.put("birthyear", jObject.getString("birthyear"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
编辑:日志中没有错误。现在的错误处理程序说“请求失败:org.json.JSONException:类型org.json.jsonArray的值无法转换为jsonobject”。
答案 0 :(得分:0)
从您的网址中,数据是JSON数组。您正在尝试从JSONArray的String创建JSONObject。它不能以这种方式工作。改为创建一个JSONArray。
此外,仍然在您的网址中,您的json中没有任何关键字“帖子”。