Unable to open URLConnection in android

I am trying to get the response code by opening URLConnection. It was successfully creating URLConnection in java console program, but when I tried this code in android, this function always returns -1 as resCode, which means it cannot be able to do URLConnection in android. Is there any solution to get the response code for a site segment?

     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 have set internet permission in android.permission.INTERNET manifest

+3


source to share


3 answers


You have opened the connection twice. And there is no response code = -1

. It will be returned as 200

when HTTP

ok. Try to open connection with only HttpURLConnection

and get response code:



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

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

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

      

+1


source


From the documentation for the HttpURLConnection # getResponseCode () method :

Returns -1 if the code cannot be recognized from the response (i.e. the response is invalid HTTP).



You either get an invalid HTTP response here, or your request throws an exception and leaves it resCode

in its original state.

+1


source


I've 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.

0


source







All Articles