Android HttpURLConnection: Handle HTTP redirects

后端 未结 2 1189
一生所求
一生所求 2020-12-31 11:49

I\'m using HttpURLConnection to retrieve an URL just like that:

URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) u         


        
2条回答
  •  旧时难觅i
    2020-12-31 12:25

    Simply call getUrl() on URLConnection instance after calling getInputStream():

    URLConnection con = new URL(url).openConnection();
    System.out.println("Orignal URL: " + con.getURL());
    con.connect();
    System.out.println("Connected URL: " + con.getURL());
    InputStream is = con.getInputStream();
    System.out.println("Redirected URL: " + con.getURL());
    is.close();
    

    If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

    HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
    con.setInstanceFollowRedirects(false);
    con.connect();
    int responseCode = con.getResponseCode();
    System.out.println(responseCode);
    String location = con.getHeaderField("Location");
    System.out.println(location);
    

提交回复
热议问题