问题解决了。原因是我忘了向应用程序授予Internet权限。
我想实现的基本功能是
我使用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();
}
}
答案 0 :(得分:1)
您尚未指定请求方法。我假设您想从服务器获取结果。
HttpURLConnection conn = (HttpURLConnection ) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(10000); // millis
conn.setConnectTimeout(15000); // millis
conn.setDoOutput(true);
conn.connect();
int response = conn.getResponseCode();
if (response == HttpStatus.SC_OK) {
.....