无法在Android中使用HttpClient和HttpGet

时间:2013-03-01 14:13:53

标签: android

我想使用yahoo api找出天气信息。但是,执行以下语句时出现错误。我可以提一些解决方法吗?感谢。

HttpClient httpClient = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(queryString);

HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();  // <--- error here

我已将互联网许可添加到mainfest。

03-01 22:06:27.310: E/AndroidRuntime(27723): FATAL EXCEPTION: main
03-01 22:06:27.310: E/AndroidRuntime(27723): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidYahooWeatherDOM/com.exercise.AndroidYahooWeatherDOM.AndroidYahooWeatherDOMActivity}: android.os.NetworkOnMainThreadException
03-01 22:06:27.310: E/AndroidRuntime(27723):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
03-01 22:06:27.310: E/AndroidRuntime(27723):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
03-01 22:06:27.310: E/AndroidRuntime(27723):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
03-01 22:06:27.310: E/AndroidRuntime(27723):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
03-01 22:06:27.310: E/AndroidRuntime(27723):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-01 22:06:27.310: E/AndroidRuntime(27723):    at android.os.Looper.loop(Looper.java:137)

1 个答案:

答案 0 :(得分:0)

您需要使用单独的线程或更好的AsyncTask来进行Http连接

例如:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}