HttpURLConnection类抛出异常 [英] HttpURLConnection is throwing exception

查看:166
本文介绍了HttpURLConnection类抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code连接 HTTP

Here is my code to connect HTTP.

URL url = new URL("http://www.google.com");
              HttpURLConnection con = (HttpURLConnection) url.openConnection();
              con.setDoOutput(true);
              String responseMsg = con.getResponseMessage();
              int response = con.getResponseCode();

这是扔 android.os.NetworkOnMainThreadException

请帮忙。

推荐答案

android.os.NetworkOnMainThreadException是因为你在你的主UI线程进行网络通话。相反,使用AsyncTask的。

android.os.NetworkOnMainThreadException occurs because you are making network call on your main UI Thread. Instead use a asynctask.

的AsyncTask的文档。<一个href=\"http://developer.android.com/reference/android/os/AsyncTask.html\">http://developer.android.com/reference/android/os/AsyncTask.html.

Documentation of asynctask.http://developer.android.com/reference/android/os/AsyncTask.html.

呼叫的AsyncTask在UI线程。

Call AsyncTask in your UI Thread.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new MyDownloadTask().execute();

}

class MyDownloadTask extends AsyncTask<Void,Void,Void>
{


    protected void onPreExecute() {
      //display progress dialog.

 }
    protected Long doInBackground(Void... params) {
          URL url = new URL("http://www.google.com");
          HttpURLConnection con = (HttpURLConnection) url.openConnection();
          con.setDoOutput(true);
          String responseMsg = con.getResponseMessage();
          int response = con.getResponseCode();
     return null;
 }



 protected void onPostExecute(VOid result) {
   // dismiss progress dialog and update ui
 }
}

注意:AsyncTask的设计是围绕主题和Handler一个辅助类,并不构成通用线程框架。 AsyncTasks最好应(至多几秒钟。)可用于短期操作。如果您需要保持对长时间运行的线程,强烈建议您使用的java.util.concurrent中pacakge如提供的各种API遗嘱执行人,并ThreadPoolExecutor的FutureTask提供。

Note : AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

这是另一种在robospice AsyncTask的。 https://github.com/octo-online/robospice

An alternative to asynctask in robospice. https://github.com/octo-online/robospice.

一些robospice的功能。

Some of the features of robospice.

1.executes异步(在后台AndroidService)网络请求。(例如:使用Spring的Andr​​oid REST请求)

1.executes asynchronously (in a background AndroidService) network requests (ex: REST requests using Spring Android).

2.is强类型!你让使用POJO您的要求,你会得到的POJO的申请结果。

2.is strongly typed ! You make your requests using POJOs and you get POJOs as request results.

3.enforce没有约束既不使用也不要求你在项目中使用活动课的POJO。

3.enforce no constraints neither on POJOs used for requests nor on Activity classes you use in your projects.

4.caches结果(以JSON既杰克逊和GSON或XML或纯文本文件或二进制文件,即使使用ORM精简版)。

4.caches results (in Json with both Jackson and Gson, or Xml, or flat text files, or binary files, even using ORM Lite).

5.notifies您的网络请求的结果,当且仅当他们还活着。

5.notifies your activities (or any other context) of the result of the network request if and only if they are still alive

6.no内存泄漏可言,如Android装载机,不像Android的AsyncTasks通知他们的UI线程的活动。

6.no memory leak at all, like Android Loaders, unlike Android AsyncTasks notifies your activities on their UI Thread.

7.uses一个简单而健壮的异常处理模式。

7.uses a simple but robust exception handling model.

这篇关于HttpURLConnection类抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆