2014-12-24 78 views
1

發送POST請求時,我有這樣的方法:錯誤的Android

public String post(String urlParameters, String url) throws IOException{ 
     URL obj = new URL(url); 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("User-Agent", "Chrome"); 
     con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
     con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     con.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
     wr.writeBytes(urlParameters); 
     wr.flush(); 
     wr.close(); 
     int responseCode = con.getResponseCode(); 
     System.out.println("\nSending 'POST' request to URL : " + url); 
     System.out.println("Post parameters : " + urlParameters); 
     System.out.println("Response Code : " + responseCode); 
     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     String inputLine; 
     StringBuffer response = new StringBuffer(); 
     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
     in.close(); 
     return response.toString(); 
    } 

它編譯罰款,但它不會運行。聯合國清單中存在互聯網許可。 它說(在logcat中)

12-24 14:59:31.028 E/AndroidRuntime(30941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fliife.bitvisitorbot/com.fliife.bitvisitorbot.MainActivity}: android.os.NetworkOnMainThreadException 

我能做些什麼?

回答

0

當應用程序嘗試在其主線程上執行聯網操作時會拋出此異常,因爲網絡操作可能涉及不可預知的延遲。爲了防止這種情況導致糟糕的用戶體驗,請始終在UI的單獨線程上執行網絡操作。 AsyncTask類提供了從UI線程中觸發新任務的最簡單方法之一。

參見:AsyncTask

只是爲了您的信息,這只是拋出應用針對蜂窩SDK或更高。針對早期SDK版本的應用程序允許在其主要事件循環線程上進行聯網,但非常不鼓勵。

0

你需要一個的AsyncTask

public class Start extends AsyncTask<String, Integer, String>{ 

    protected void onPreExecute() { 
     dialog = new ProgressDialog(MainActivity.this); //your activity 
     dialog.setTitle("Downloading data in progress"); 
     dialog.setMessage("Wait few seconds..."); 
     dialog.show(); 
    } 

    protected String doInBackground(String... urls){ 

     // inside this method you must call your post() method 
    } 

    protected void onPostExecute(final String result) { 

      dialog.dismiss(); 
     // inside this one you can update your items 

    } 
} 

並稱之爲:

new Start().execute();