我在这里有这段代码,我从http://mobilesiri.com/json-parsing-in-android-using-android-studio/获取并修改它以供我自己使用。
public String makeWebServiceCall(String addr, int requestMethod) {
URL url;
String response = "";
try {
url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestMethod == Constant.GET) {
conn.setRequestMethod("GET");
} else if (requestMethod == Constant.DELETE) {
conn.setRequestMethod("DELETE");
}
int reqResponseCode = conn.getResponseCode();
if ((requestMethod == Constant.GET || requestMethod == Constant.DELETE) && reqResponseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (MalformedURLException murle) {
Log.e(MalformedURLException.class.getName(), murle.getMessage());
} catch (IOException ioe) {
Log.e(IOException.class.getName(), ioe.getMessage());
}
return response;
}
把它和库一起放在一个普通的Java环境中,我可以得到这种形式的输出
{"status":"FOUND","data":[{"category_id":3,"category_name":"Experience Sharing Area"},{"category_id":4,"category_name":"Frequently Asked Questions"},{"category_id":1,"category_name":"General Pain Advice"},{"category_id":2,"category_name":"Pain Categorization Section"}]}
把它放在 Android 中解析数据,我得到 JSONException - org.json.JSONException: End of input at character 0 of
这是我实现它的地方。
protected Void doInBackground(Void... voids) {
WebRequest webReq = new WebRequest();
String jsonStr = webReq.makeWebServiceCall(Constant.WEB_SERVER_ADDR + Constant.GET_CATEGORY, Constant.GET);
Log.d("URL:", Constant.WEB_SERVER_ADDR + Constant.GET_CATEGORY);
Log.d("Response:", " > " + jsonStr);
categoryList = parseJSON(jsonStr);
return null;
}
这有什么问题吗?