2012-01-06 86 views
0

我使用的類可從經由PHP/JSON數據的基礎上使用HTTP POST &獲取數據並將其轉換爲一個字符串。錯誤與HTTP POST連接

問題是我在LogCat中獲得 "Error in http connection android.os.NetworkOnMainThreadException"。我在模擬器上測試了這一點,並且使用了正確的端口地址。我知道這是因爲該端口在應用程序的其他部分工作正常(從本地加載HTML)。如果我在桌面瀏覽器中運行php文件,它運行良好。我也知道,權限設置是否正確在MySQL 10.0.2.2 &用戶在登錄的PHP文件中設置。

所以我的問題是:有沒有人翻過了同樣的問題,如果是的話,你想通了,問題是什麼或應該尋找什麼其他我什麼想法?

日Thnx您的幫助!

public void loadQuery(String p) { 

     String qO = getIntent().getStringExtra("QUERY_ORDER"); 

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     // http post 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      // HttpPost httppost = new HttpPost("http://10.0.2.2/Andaero/php/" + 
      // p + qO + ".php"); 

      //Hard coded the php link to make sure --> 

      HttpPost httppost = new HttpPost(
        "http://10.0.2.2/Andaero/php/regulatory_list_ASC.php"); 

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error in http connection " + e.toString()); 
     } 

     // convert response to string 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      sb = new StringBuilder(); 
      sb.append(reader.readLine() + "\n"); 

      String line = "0"; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      result = sb.toString(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error converting result " + e.toString()); 
     } 

     setListAdapter(new QueryAdapter(this, result)); 
    } 

回答

2

看來你可能在你的應用的主線程上進行網絡操作(這是拋出異常的常見原因)。

你不應該這樣做。主線程應該只專用於用戶交互,並且所有的網絡交互應該卸載到輔助線程(例如,使用AsyncTask)。

欲瞭解更多信息,很好看的是: http://developer.android.com/guide/practices/design/responsiveness.html

+0

日Thnx。你能舉出一個關於如何把它放在另一個線程上的例子嗎? - 我還是那麼做過。 – CelticParser 2012-01-06 19:10:08