2016-05-30 79 views
-1

我嘗試設置HttpURLConnection。我使用Google documentation的語法。我想將字符串'phonenumber'和字符串'password'發送到Web服務器。這是我的java文件:嘗試在android studio中設置HttpURLConnection時出現'未處理的異常'

public class Login extends AppCompatActivity { 

    @Override 
    protected void onCreate(final Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 

     EditText phonenumberText = (EditText)findViewById(R.id.phonenumberText); 
     EditText passwordText = (EditText)findViewById(R.id.passwordText); 
     String phonenumber = phonenumberText.getText().toString(); 
     String password = passwordText.getText().toString(); 
     String web = "webadress/login/tel=" + phonenumber + "&password =" + password; 

     URL url = new URL(web); 
     HttpURLConnection client = (HttpURLConnection) url.openConnection(); 

     try{ 
      InputStream in = new BufferedInputStream(client.getInputStream()); 
      readStream(in); 
      finally { 
       client.disconnect(); 
      }//finally 
     }//try 

    }//onCreate 
}//Login 

在AndroidManifest我包括

<uses-permission android:name="android.permission.INTERNET" /> 

,但我得到的方法url.openConnection()client.getInputStream()readStream(in)錯誤未處理的異常:java.io.IOException的。對於new URL(web),我得到錯誤未處理的異常:java.net.MalformedURLException。幫助將不勝感激。

+0

閱讀此:https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html –

+0

您正在調用拋出檢查異常的方法,因此您需要捕獲它們。這就是它的工作原理。 – Mena

+0

我是一名初學者:捕捉方法的含義是什麼? – Izotz

回答

0

您需要將全部語句包含在try/catch塊中,而不僅僅是最後兩個中的IoException。事情是這樣的:

//your existing code.. 

HttpURLConnection client = null; 

try{ 
    URL url = new URL(web); 
    client = (HttpURLConnection) url.openConnection(); 

    InputStream in = new BufferedInputStream(client.getInputStream()); 
    readStream(in); 

} catch (MalformedURLException e) { 
    //bad URL, tell the user 
} catch (IOException e) { 
    //network error/ tell the user 
} finally { 
    client.disconnect(); 
} 

具體而言:在catch塊用於「捕獲」了異常,例如。當出現網絡錯誤或URL無效時,控制權將從您可以從的地方轉移到catch區塊。告訴用戶有錯誤。

+0

謝謝,但它無法解決客戶端。只在'client.disconnect()' – Izotz

+0

@Izotz,修正,抱歉。你需要把'HttpURLConnection客戶端'放在catch塊之外 – JonasCz

+0

finally語句中的變量'client'可能沒有初始化' – Izotz

相關問題