Android HttpURLConnection AndroidRuntime错误

时间:2013-05-30 15:39:23

标签: java android android-asynctask httpurlconnection

问题解决了。原因是我忘了向应用程序授予Internet权限。

我想实现的基本功能是

  1. 获取网址并连接到远程服务器
  2. 从远程服务器获取结果并在TextView上显示结果
  3. 我使用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();
                }
    
        }
    

1 个答案:

答案 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) {
       .....