Java HttpURLConnectionリダイレクトの例

Java HttpURLConnectionはリダイレクトの例に従います

301-redirect

HttpURLConnectionのフォローリダイレクトは単なる指標であり、実際には「実際の」httpリダイレクトを行うのに役立ちません。それでも、手動で処理する必要があります。

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setInstanceFollowRedirects(true);  //you still need to handle redirect manully.
HttpURLConnection.setFollowRedirects(true);

1. Java Httpリダイレクトの例

サーバーが元のURLから別のURLにリダイレクトされる場合、応答コードは301: Moved Permanentlyまたは302: Temporary Redirectである必要があります。 And you can get the new redirected url by reading the “Location” header of the HTTP response header.

たとえば、通常のHTTP Twitter Webサイト–http://www.twitter.comにアクセスすると、HTTPS Twitter Webサイト–https://www.twitter.comに自動的にリダイレクトされます。

HttpRedirectExample –完全なJavaはリダイレクトの例に従います。説明はコメントを参照してください。

package com.example.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRedirectExample {

  public static void main(String[] args) {

    try {

    String url = "http://www.twitter.com";

    URL obj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
    conn.setReadTimeout(5000);
    conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
    conn.addRequestProperty("User-Agent", "Mozilla");
    conn.addRequestProperty("Referer", "google.com");

    System.out.println("Request URL ... " + url);

    boolean redirect = false;

    // normally, 3xx is redirect
    int status = conn.getResponseCode();
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
        redirect = true;
    }

    System.out.println("Response Code ... " + status);

    if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // get the cookie if need, for login
        String cookies = conn.getHeaderField("Set-Cookie");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
        conn.setRequestProperty("Cookie", cookies);
        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        conn.addRequestProperty("User-Agent", "Mozilla");
        conn.addRequestProperty("Referer", "google.com");

        System.out.println("Redirect to URL : " + newUrl);

    }

    BufferedReader in = new BufferedReader(
                              new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer html = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        html.append(inputLine);
    }
    in.close();

    System.out.println("URL Content... \n" + html.toString());
    System.out.println("Done");

    } catch (Exception e) {
    e.printStackTrace();
    }

  }

}

出力

Request URL ... http://www.twitter.com
Response Code ... 301
Redirect to URL : https://twitter.com/
URL Content...