我正在运行asyncTask
以从HttpPost
检索JSON对象数组。
来自webservice的输出是:
[
{
"id": 1,
"question": "What town were you born in?"
},
{
"id": 2,
"question": "What is your mothers maiden name?"
},
{
"id": 3,
"question": "Who was your childhood hero?"
}
]
但是得到JSONException
:
org.json.JSONException: End of input at character 0 of
以下代码中的JArray
:
JSONArray JArray;
Context ra;
public SecurityQuestionsTask(Context _registerActivity) {
ra = _registerActivity;
JArray = new JSONArray();
}
@Override
protected Long doInBackground(String... langs) {
Long result = 0L;
String lang = Locale.getDefault().getLanguage();
String[] langArray = {"en", "de", "fr"};
if (!Arrays.asList(langArray).contains(lang)) {
lang = "en";
}
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://webservice.com/api/v1/securityquestions?lang=" + lang);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
JSONString = EntityUtils.toString(response.getEntity(), "UTF-8");
JArray = new JSONArray(JSONString);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
publishProgress("Retrieving security questions...");
return result;
}
我是否正确地将response
解析为JSONArray
?
编辑:
这就是网络服务响应的方式:
return Response.status(200).entity(json.toString()).build();
答案 0 :(得分:0)
线索出现在问题标题中!
我必须使用HttpGet
而不是HttpPost
来设置我的网络服务。
所以这一行:
HttpPost httppost = new HttpPost("http://webservice.com/api/v1/securityquestions?lang=" + lang);
必须改为:
HttpGet httpGet = new HttpGet("http://webservice.com/api/v1/securityquestions?lang=" + lang);
答案 1 :(得分:-1)
如果String
回复与您发布的回复相似,请尝试
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
JSONArray jsonArr = new JSONArray(resp);