2012-10-17 96 views
0

所以,當我嘗試運行下面的代碼,我永遠不會通過響應線。我究竟做錯了什麼?我已在我的清單文件中允許訪問互聯網。我一定會錯過一些巨大的東西,因爲我看過大約100個與我的代碼完全相同的類似示例。我甚至爲了運行這幾行而構建了示例項目,它們都以相同的方式運行。請請幫助(最終目標是使以https這項工作很好,但任何進展,使工作與HTTP是我不夠好)HttpResponse不會工作

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) 
+0

當在最後一個catch語句中捕獲到異常時,它是什麼類型的異常? – boztalay

+0

我的catch和log語句設置是否正確(仍然試圖更好地理解log cat)?以上是我的相關(在我眼中)logcat結果 –

回答

0

完美,這就是我一直在尋找。查找NetworkOnMainThreadException,我們得到this page。這意味着您無法在應用程序的主線程上運行HTTP請求,但只能在您定位到Honeycomb時運行。

因此,解決這個問題的最簡單方法是針對不同的Android版本。也許2.3,或者達到Jellybean。另一種解決方法是設置一個AsyncTask來運行HTTP請求。

如果它適用於您定位不同的Android版本,請執行此操作。如果沒有,我可以用AsyncTask來幫助你。但是,請記住,他們強烈建議您在您的主線程上運行聯網請求,而不是不要

至於AsyncTasks,最好的轉身地方總是Android documentation

其基本思想是擴展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); 
+0

targetting 2.3是解決這個問題的非常懶惰和骯髒的方法。 您應該始終定位最新版本的Android。 使用AsyncTask是解決此問題的正確方法。 – Teovald

+0

太棒了。我很想了解更多關於asynctasks的信息。幾個月前我剛開始自學編程,但我學到了一些關於線程的知識。我做了一個java swing應用程序,它在UI做了其他事情時進行了計算(希望異步是相似的)。你能指出我的方向是否正確,當我準備好時,我可以回覆你嗎? –

+0

當然,我編輯我的答案包括AsyncTask的東西。 – boztalay