Izotz Izotz - 6 months ago 40
Android Question

'Unhandled exception' when trying to set up a HttpURLConnection in android studio

I try to set up a HttpURLConnection. I use the syntax from the Google documentation. I want to send the string 'phonenumber' and the string 'password' to a webserver. This is my .java file:

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


In the AndroidManifest I included

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


But I get for the methods
url.openConnection()
,
client.getInputStream()
and
readStream(in)
the error Unhandled exception: java.io.IOException. For
new URL(web)
I get the error Unhandled exception: java.net.MalformedURLException. Help would be appreciated.

Answer

You need to wrap the all statements which throw an IoException in a try / catch block, not just the last two. Something like this:

//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();
}

To be specific: the catch blocks are used to "catch" an exception, eg. when there's a network error or the URL is not valid, control is transferred to the catch block, from where you could eg. tell the user that there was an error.