-3

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

HttpClient httpClient = new DefaultHttpClient();

HttpGet httpGet = new HttpGet(queryString);

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

我已将 Internet 权限添加到 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)
4

1 回答 1

0

You need to use a separate thread or better an AsyncTask, to do an Http connection

For example:

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");
 }
}
于 2013-03-01T14:18:08.590 回答