从Android的REST服务器获取JSON时发生FileNotFound异常
问题描述:
从REST服务器获取JSON
数据时遇到问题。 Web浏览器返回JSON
数据here正确,但下面的代码将导致FileNotFound
例外:从Android的REST服务器获取JSON时发生FileNotFound异常
private void getJSON(String url) {
class GetJSONServices extends AsyncTask<String, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = new ProgressDialog(ServicesActivity.this);
loading.setTitle("");
loading.setMessage("Getting your services...");
loading.setCancelable(false);
loading.show();
}
@Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
Log.e("Do In Background", getStackTrace(e));
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
Toast.makeText(ServicesActivity.this, s, Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Log.e("On Post Execute", getStackTrace(e));
}
}
}
GetJSONServices gj = new GetJSONServices();
gj.execute(url);
}
此外,AndroidManifest.xml中有INTERNET权限,其余服务器允许CORS。是什么导致了这个错误,我该如何解决?
编辑:我使用HttpURLConnection,而不是删除的HttpClient。
答
我使用commons.io.2.4
库在这个例子中,
显然我没有得到的错误,你可以看到输出,
public static void main(String[] args) {
try {
URL url = new URL("http://eventoserver-ecinauce.rhcloud.com/songwol/services");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
String result = IOUtils.toString(connection.getInputStream());
System.out.println(""+result);
} catch (Exception e) {
// TODO: handle exception
}
}
输出
{
"3": {
"id": 3,
"info": null,
"name": "singer",
"owner": 1,
"packages": {},
"reviews": {},
"type": "performer"
}
}
什么是'sb.toString()'的输出? –
[在Web服务中读取Json在Android中休息。 FileNotFoundException](http://*.com/questions/11978412/reading-json-in-webservice-rest-in-android-filenotfoundexception) – Sree
发布logcat – Pankaj