有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java代理和web服务身份验证

我试图访问一个需要身份验证的web服务,但我也支持一个需要自己身份验证的代理。 当web服务URL没有身份验证时,可以通过代理服务器获取结果。但是,当web服务需要身份验证时,它根本不起作用。我得到以下错误:

Exception in thread "main" java.net.ProtocolException: Server redirected too many  times

下面是我的代码:

Authenticator auth = new Authenticator() {
    public PasswordAuthentication getPasswordAuthentication() {

    if(getRequestorType() == Authenticator.RequestorType.PROXY)
    {   //for proxy
      return (new PasswordAuthentication("user", "pass".toCharArray()));
    }
    else
    {  // for web service   
     return (new PasswordAuthentication("user2", "pass2".toCharArray())); 
     }
     }
     };
    Authenticator.setDefault(auth);
    SocketAddress addr = new
                         InetSocketAddress("proxy addr", port no);

    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
    URL url = new URL("...");
    URLConnection yc = query.openConnection(proxy);
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            yc.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
    in.close();

这是我的第一个问题。任何帮助都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    URL不一样。请求URL使用HTTP,重定向URL使用HTTPS。可能发生的情况是,服务将重定向请求发送到代理,但代理仍然不断地请求HTTP URL。有些代理是known to exhibit这种行为

    在初始请求中切换到使用HTTPS。我对相关服务器的HTTP调用导致重定向到HTTPS,而HTTPS调用导致401

    HTTP/1.1 401 The authorization type you provided is not supported. Only Basic and OAuth are supported