I'm beginning my adventure with android and trying make app which will download data from website after logging in. I have written method to connecting with website in this way:
public class ConnectWebsite extends AsyncTask<String, Void, String> {
String server_response;
public static final int CONNECTON_TIMEOUT_MILLISECONDS = 60000;
@Override
protected String doInBackground(String... strings) {
String result = "";
InputStream is = null;
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setConnectTimeout(CONNECTON_TIMEOUT_MILLISECONDS);
urlConnection.setReadTimeout(CONNECTON_TIMEOUT_MILLISECONDS);
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if(responseCode != HttpsURLConnection.HTTP_OK) {
throw new IOException("HTTP error code: " + responseCode);
}
is = urlConnection.getInputStream();
if (is != null) {
// Converts Stream to String with max length of 500.
result = readStream(is, 500);
}
} catch (MalformedURLException e) {
Log.d("ConnectWebsite ", Log.getStackTraceString(e));
e.printStackTrace();
} catch (IOException e){
Log.d("ConnectWebsite ", Log.getStackTraceString(e));
e.printStackTrace();
}
return result;
}
private String readStream(InputStream stream, int maxLength) throws IOException {
...
}
Unfortunately, when debugger will come to urlConnection.connect() App throw exception "Could not execute method for android:onClick"
EDIT: Fuction which services onclick
public void login(View w){
Toast.makeText(this, "Login...", Toast.LENGTH_LONG).show();
ConnectWebsite conn = new ConnectWebsite();
String url = "http://examplewebsite.com";
conn.execute(url);
}
EDIT V2:
It almost works good, I had to declare uses-permission in manifest like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="myProject">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>