0

因此,当我尝试运行以下代码时,我永远无法超过响应行。我究竟做错了什么?我在清单文件中允许访问互联网。我一定遗漏了一些巨大的东西,因为我看到了大约 100 个与我具有完全相同代码的类似示例。我什至构建了示例项目来运行这几行代码,它们的行为方式都相同。请帮助(最终目标是使这项工作也与 https 一起工作,但任何进展使其与 http 一起工作对我来说已经足够了)

try{

                        HttpClient myHttpClient = new DefaultHttpClient();
                        HttpPost myHttpPost = new HttpPost("http://www.siirretytnumerot.fi/index.html?clientLanguage=eng");
                       //^Ive tried about 10 different sites (http and https) none of them work

                        //NEVER GETS PAST THE LINE BELOW, JUMPS TO THE LAST CATCH BLOCK OF THE EXCEPTION
                        HttpResponse response = myHttpClient.execute(myHttpPost);
                        //NEVER GETS PAST THE ABOVE LINE...

                        String data = EntityUtils.toString(response.getEntity());
                        json= new JSONObject(data);
                    //parse the JSONObject
                       } catch (UnsupportedEncodingException e){e.printStackTrace();}
                         catch (ClientProtocolException e){e.printStackTrace();}
                         catch (IOException e){e.printStackTrace();}
                         catch (JSONException e) {e.printStackTrace();}
                         catch (NullPointerException e){ Log.e("My APP", "exception: " + e.getMessage());}
                         catch (Exception e ) {Log.e("My APP", "exception", e);} 


10-17 15:31:41.423: E/My APP(974): exception
10-17 15:31:41.423: E/My APP(974): android.os.NetworkOnMainThreadException
10-17 15:31:41.423: E/My APP(974):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
10-17 15:31:41.423: E/My APP(974):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-17 15:31:41.423: E/My APP(974):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-17 15:31:41.423: E/My APP(974):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-17 15:31:41.423: E/My APP(974):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-17 15:31:41.423: E/My APP(974):  at com.example.httpstuff.MainActivity$1.onClick(MainActivity.java:44)
10-17 15:31:41.423: E/My APP(974):  at android.view.View.performClick(View.java:3511)
10-17 15:31:41.423: E/My APP(974):  at android.view.View$PerformClick.run(View.java:14105)
10-17 15:31:41.423: E/My APP(974):  at android.os.Handler.handleCallback(Handler.java:605)
10-17 15:31:41.423: E/My APP(974):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-17 15:31:41.423: E/My APP(974):  at android.os.Looper.loop(Looper.java:137)
10-17 15:31:41.423: E/My APP(974):  at android.app.ActivityThread.main(ActivityThread.java:4424)
10-17 15:31:41.423: E/My APP(974):  at java.lang.reflect.Method.invokeNative(Native Method)
10-17 15:31:41.423: E/My APP(974):  at java.lang.reflect.Method.invoke(Method.java:511)
10-17 15:31:41.423: E/My APP(974):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-17 15:31:41.423: E/My APP(974):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-17 15:31:41.423: E/My APP(974):  at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

0

完美,这就是我想要的。查找 NetworkOnMainThreadException,我们得到这个页面。这意味着您不能在应用程序的主线程上运行 HTTP 请求,但只能在以 Honeycomb 为目标时运行。

因此,解决此问题的最简单方法是针对不同的 Android 版本。也许是 2.3,或者到 Jellybean。另一种解决方法是设置一个 AsyncTask 来运行 HTTP 请求。

如果它适用于您针对不同的 Android 版本,请执行此操作。如果没有,我可以帮助您解决 AsyncTask。但是,请记住,他们强烈建议您不要在主线程上运行网络请求。

至于 AsyncTasks,最好的地方总是Android 文档

基本思想是扩展 AsyncTask 类,这使您实现 doInBackground 方法。然后创建新类的实例,并调用 execute()。这是文档中的代码片段:

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");
    }
}

new DownloadFilesTask().execute(url1, url2, url3);
于 2012-10-17T15:55:39.853 回答