2017-08-28 45 views
-3

我想在這樣的android工作室做POST請求。如何在Android Studio中執行HTTP POST請求?

btnSignin.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 


      //submitForm(); 
      tryLogin("[email protected]", "Test1234"); 
     } 
    }); 





protected void tryLogin(String mUsername, String mPassword) 
{ 
    HttpURLConnection connection; 
    OutputStreamWriter request = null; 

    URL url = null; 
    String response = null; 
    String parameters = "email="+mUsername+"&password="+mPassword; 
    StrictMode.ThreadPolicy policy = new 
    StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

    try 
    { 
     url = new URL("URL"); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     connection.setRequestMethod("POST"); 

     request = new OutputStreamWriter(connection.getOutputStream()); 
     request.write(parameters); 
     request.flush(); 
     request.close(); 
     String line = ""; 
     InputStreamReader isr = new InputStreamReader(connection.getInputStream()); 
     BufferedReader reader = new BufferedReader(isr); 
     StringBuilder sb = new StringBuilder(); 
     while ((line = reader.readLine()) != null) 
     { 
      sb.append(line + "\n"); 
     } 
     // Response from server after login process will be stored in response variable. 
     response = sb.toString(); 
     // You can perform UI operations here 
     Toast.makeText(this,"Message from Server: \n"+ response, 0).show(); 
     isr.close(); 
     reader.close(); 

    } 
    catch(IOException e) 
    { 
     // Error 
    } 

但應用程序崩潰,我得到這樣的錯誤 -

致命異常:主要

過程:測試,PID:19928在

android.os.NetworkOnMainThreadException android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:> 1425)

在java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)

我已經在清單文件中添加Internet權限。 這是因爲我沒有通過AsyncTask完成它? 我該如何解決這個問題?

+0

使用的AsyncTask ..... –

+1

你不能在主線程上執行網絡操作..所以你要使用asynctask – AbhayBohra

+1

使用單獨的線程進行網絡操作。 asynctask在這種情況下很容易 – AAA

回答

-1

,你可以把你的網絡運行在這個線程或使用的AsyncTask或任何其他庫

new Thread(new Runnable() { 
      public void run(){   
      txt1.setText("Thread!!"); 
      } 
     }).start();