问题解决了。原因是我忘记给应用程序授予 Internet 权限。
我要实现的基本功能是
- 获取 URL 并连接到远程服务器
- 从远程服务器获取结果并在 TextView 上显示结果
我使用 asynctask 从远程服务器加载结果。但是,我已经调试以下代码几个小时,仍然不知道哪里出了问题。谁能帮我吗?
private class ReportLocationTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
return reportLoc(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
@Override
protected void onPostExecute(String result) {
mActivityIndicator.setVisibility(View.GONE);
mReport.setText(result);
}
}
private String reportLoc(String urlstring) throws IOException{
URL url = new URL(urlstring);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try{
InputStream in = new BufferedInputStream(conn.getInputStream());
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
//System.out.println(read);
sb.append(read);
read =br.readLine();
}
return sb.toString();
}
finally {
conn.disconnect();
}
}