failed to open URLConnection in android

6.9k Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

You opened the connection twice. And there is no response code = -1. It will be returned as 200 when HTTP is OK. Try to open the connection with HttpURLConnection only and get the response code:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

// get the response code, returns 200 if it's OK
int responseCode = connection.getResponseCode();

if(responseCode == 200) {
    // response code is OK
    in = connection.getInputStream();
}else{
    // response code is not OK
}
1
On

From the documentation on HttpURLConnection#getResponseCode() method:

Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

You either get a malformed HTTP response here, or your request throws an Exception, leaving resCode in its initial state.

2
On

I had the same problem before.

I put this at the beginning of my code

// To keep this example simple, we allow network access
// in the user interface thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();
StrictMode.setThreadPolicy(policy);

And It works.