浏览器获取当前URL或响应头

时间:2011-02-09 12:21:41

标签: java url browser redirect header

如何从SWT浏览器对象或java中的任何其他浏览器获取响应标头或浏览器的当前URL(重定向到另一个页面)?

2 个答案:

答案 0 :(得分:0)

Also see more here

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpResponseHeaderDemo {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.domain.com/index.html");
            URLConnection connection = url.openConnection();

            Map responseMap = connection.getHeaderFields();
            for (Iterator iterator = responseMap.keySet().iterator(); iterator.hasNext();) {
                String key = (String) iterator.next();
                System.out.print(key + " = ");

                List values = (List) responseMap.get(key);
                for (int i = 0; i < values.size(); i++) {
                    Object o = values.get(i);
                    System.out.print(o + ", ");
                }
                System.out.println("");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

假设你已经做过类似的事情:

URI uri = new URI("http://www.foo.bar");
HttpURLConnection conn  = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();         
responseCode = conn.getResponseCode();
is = conn.getInputStream();
// read from IS

然后你可以这样做:

conn.getURL();

获取重定向的响应网址。