I'm trying to get the response code by opening a URLConnection, It was successfully making URLConnection in java console program, but when I tried this code in android this function always returns a -1 as resCode which means it couldn't able to make a URLConnection in android. Is there any solution to get website sever response code?
public static int openHttpConnection(String urlStr) {
InputStream in = null;
int resCode=-1;
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException ("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (MalformedURLException e) {
Log.d("Exception: ", "MalformedURLException");
} catch (IOException e) {
Log.d("Exception: ", "IOException");
}
catch(Exception e){
Log.d("Exception: ", "UnknownException");
}
return resCode;
}
I've set internet permission in the manifest android.permission.INTERNET
You opened the connection twice. And there is no response code =
-1
. It will be returned as200
whenHTTP
is OK. Try to open the connection withHttpURLConnection
only and get the response code: