【问题标题】:When i change my api level my http request doesn't work当我更改我的 api 级别时,我的 http 请求不起作用
【发布时间】:2014-06-10 08:37:09
【问题描述】:

当我的 api 级别设置为 8 时,一切正常。但是当我尝试将 minSdkVersion 设置为 11 时,我获取 xml 的 http 请求不起作用。我在 if 上有一个例外。 代码如下:

URL url;
    String ciao="";
    try {
      url = new URL("myurl");

      URLConnection connection = url.openConnection(); 

      HttpURLConnection httpConnection = (HttpURLConnection)connection; 
      int responseCode = httpConnection.getResponseCode(); 

      if (responseCode == HttpURLConnection.HTTP_OK) { 
        InputStream in = httpConnection.getInputStream(); 
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(in);
        DOMSource domSource = new DOMSource(dom);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        ciao=writer.toString();
      }
        }
    catch(Exception e)
    {

    }
    return ciao;

【问题讨论】:

  • 你得到了什么异常?
  • 发布日志猫。尝试清理项目。
  • 你永远不会在 if 上遇到异常。也许在它之上。你在主线吗?在 API 11+ 中,这不再合法。

标签: android api httprequest


【解决方案1】:

原因是,从 API 11 开始,您必须在后台线程上进行所有网络访问。如果您不这样做,您将收到NetworkOnMainThreadException。引入此功能是为了防止在访问网络时 UI 无响应。

更多信息请见here

【讨论】:

    【解决方案2】:

    确保您的清单具有以下声明:

    <uses-sdk android:minSdkVersion="number-of-version-you-want" />
    

    然后

    1. 清理项目
    2. 重新构建项目。
    3. 右键单击项目并选择运行,以便生成更新版本的 APK。使用此 APK。
    4. 尝试在手机中卸载并重新安装该应用。

    注意: 使用AsyncTask 以避免主线程上出现 ANR 和 NetworkOnMainThreadException 异常。

    编辑: 请为您的 asynctask 找到代码:我还使用了 progressDialog 来显示“正在加载请稍候”类型的消息,以防 URL 调用需要更长的时间。

    public class MainActivity extends Activity
    {   
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        .... // Some code here
        // Async task can also be called from within an onclick code.
        new AsyncTaskOperation().execute("");
    }
    
    
    /* Async Task called to avoid Android Network On Main Thread Exception. Web services need to be consumed only in background.     */
    private class AsyncTaskOperation extends AsyncTask <String, Void, Void>
    {
    
        private ProgressDialog Dialog = new ProgressDialog(LoginActivity.this);
         String ciao="";
        protected void onPreExecute() {
            // Display the loading spinner
            Dialog.setMessage("Loading... Please wait.. ");
            Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            Dialog.setInverseBackgroundForced(false);
            Dialog.setCancelable(false);
            Dialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progressbar_new));
    
            Dialog.show();
        }
    
        @Override
        protected Void doInBackground(String... paramsObj) {
             try {
                  url = new URL("myurl");
    
                  URLConnection connection = url.openConnection(); 
    
                  HttpURLConnection httpConnection = (HttpURLConnection)connection; 
                  int responseCode = httpConnection.getResponseCode(); 
    
                  if (responseCode == HttpURLConnection.HTTP_OK) { 
                InputStream in = httpConnection.getInputStream(); 
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document dom = db.parse(in);
                DOMSource domSource = new DOMSource(dom);
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.transform(domSource, result);
                ciao=writer.toString();
                  }
                }
                catch(Exception e)
                {
    
                }
            return null;
        }
    
        protected void onPostExecute(Void unused) 
        {
            // Close progress dialog
            Dialog.dismiss();
            // Do actions with ciao string
    
        } // End of method onPostExecute
    
    } // End of class AsyncTaskOperation
    

    }// MainActivity 结束

    【讨论】:

    • 你能用 AsyncTask 帮忙吗?
    • @user3725188:请查找更新的代码。如果有帮助,您可以接受作为答案。
    【解决方案3】:

    API 级别 8 允许从 UI 线程发出 http 请求。但在更高版本中,在 UI 线程上发出 http 请求会抛出一个称为 NetworkonMainThread 异常的异常。要确认问题,请发布您的错误日志

    【讨论】:

      猜你喜欢
      • 2022-10-23
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多