【问题标题】:Connecting to remote URL which requires authentication using Java连接到需要使用 Java 进行身份验证的远程 URL
【发布时间】:2010-10-04 13:02:08
【问题描述】:

如何在 Java 中连接到需要身份验证的远程 URL。我正在尝试找到一种方法来修改以下代码,以便能够以编程方式提供用户名/密码,因此它不会抛出 401。

URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();

【问题讨论】:

标签: java httpurlconnection


【解决方案1】:

您可以像这样为 http 请求设置默认身份验证器:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});

另外,如果您需要更大的灵活性,您可以查看Apache HttpClient,这将为您提供更多的身份验证选项(以及会话支持等)

【讨论】:

  • 如何处理错误的身份验证事件? [例如,如果用户提供的用户名和密码验证凭据不匹配]?
  • 上面的代码可以工作,但是对于正在发生的事情是相当隐含的。那里正在进行子类化和方法覆盖,如果您想知道发生了什么,请深入研究这些类的文档。这里的代码更明确javacodegeeks
  • 是否可以为每个特定的URL.openConnection() 调用设置特定的Authenticator 而不是全局设置?
  • @Yura:没有。它必须是全球性的。但是,您可以做一些坏事,例如设置一个全局身份验证器,从线程局部变量中提取凭据,并在建立 HTTP 连接之前为每个线程设置凭据。
  • 回复@YuriyNakonechnyy...如果您使用的是Java 9 或更高版本,那么您可以致电HttpURLConnection.setAuthenticator()。不幸的是,在 Java 8 和更早版本上,Authenticator 实例是一个 JVM 范围的全局变量。见:docs.oracle.com/javase/9/docs/api/java/net/…
【解决方案2】:

有一种原生且干扰较少的替代方案,仅适用于您的呼叫。

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

【讨论】:

  • Base64 类可以由 Apache Commons Codec 提供。
  • 这种方式对我不起作用......只有@James Van Huis 的方式很好
  • 它是 Grails 和许多其他 Java 框架的“原生”,因为它们都使用 Apache Commons Libs。
  • 一般不工作,除非你.trim() 结果,或者调用不产生分块输出的方法变体。 javax.xml.bind.DatatypeConverter 似乎更安全。
  • 我在this answer引用了你的代码谢​​谢
【解决方案3】:

你也可以使用以下,不需要使用外部包:

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

【讨论】:

  • 我一直在寻找 Java 标准包中的 Base64 编码器!谢谢
  • 请注意,对于 Java9+,您可能必须--add-modules javax.xml.bind,因为他们从默认类路径中删除了包。而在 Java11+ 中它被完全删除了,你又需要一个外部依赖。这就是进步!
  • @EdRandall 现在有一个java.util.Base64,所以它确实是进步:)
【解决方案4】:

如果您使用普通登录,同时在协议和域之间输入用户名和密码,这会更简单。它也适用于登录和不登录。

示例网址:http://user:pass@domain.com/url

URL url = new URL("http://user:pass@domain.com/url");
URLConnection urlConnection = url.openConnection();

if (url.getUserInfo() != null) {
    String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
    urlConnection.setRequestProperty("Authorization", basicAuth);
}

InputStream inputStream = urlConnection.getInputStream();

请在来自 valerybodak 的评论中说明它是如何在 Android 开发环境中完成的。

【讨论】:

  • 这正是我在过去 30 分钟内一直在寻找的内容。非常感谢!
  • 如果您的用户名/密码包含特殊字符,我相信您需要对它们进行 urlencode。然后,在上面代码的 sn-p 中,您将首先通过 url.getUserInfo() 到 URLDecoder.decode() (@Peter Rader)。
  • 谢谢,但是对于 android 你应该使用 Base64 如下: String basicAuth = "Basic " + Base64.encodeToString(url.getUserInfo().getBytes(), Base64.DEFAULT); httpConn.setRequestProperty("授权", basicAuth);
  • 感谢 valerybodak 的补充!
【解决方案5】:

由于我是来这里寻找 Android-Java-Answer 的,所以我将做一个简短的总结:

  1. 使用 java.net.Authenticator 如James van Huis 所示
  2. 使用 Apache Commons HTTP 客户端,如 this Answer
  3. 使用基本 java.net.URLConnection 并手动设置 Authentication-Header,如 here 所示

如果您想在 Android 中使用 java.net.URLConnection 和基本身份验证,请尝试以下代码:

URL url = new URL("http://www.mywebsite.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc

【讨论】:

  • 谢谢。正在寻找 Android 特定的答案!
【解决方案6】:

能够使用 HttpsURLConnection 设置身份验证

           URL myUrl = new URL(httpsURL);
            HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
            String userpass = username + ":" + password;
            String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
            //httpsurlconnection
            conn.setRequestProperty("Authorization", basicAuth);

从这篇文章中获取的更改很少。 Base64 来自 java.util 包。

【讨论】:

    【解决方案7】:

    小心使用“Base64().encode()”方法,我和我的团队遇到了 400 个 Apache 错误请求问题,因为它在生成的字符串末尾添加了一个 \r\n。

    感谢 Wireshark,我们发现它可以嗅探数据包。

    这是我们的解决方案:

    import org.apache.commons.codec.binary.Base64;
    
    HttpGet getRequest = new HttpGet(endpoint);
    getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());
    
    private String getBasicAuthenticationEncoding() {
    
            String userPassword = username + ":" + password;
            return new String(Base64.encodeBase64(userPassword.getBytes()));
        }
    

    希望对你有帮助!

    【讨论】:

      【解决方案8】:

      使用此代码进行基本身份验证。

      URL url = new URL(path);
      String userPass = "username:password";
      String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or
      //String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
      HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
      urlConnection.setRequestProperty("Authorization", basicAuth);
      urlConnection.connect();

      【讨论】:

        【解决方案9】:

        对于您无法控制打开连接的代码的情况,我想提供一个答案。就像我使用 URLClassLoader 从受密码保护的服务器加载 jar 文件时所做的那样。

        Authenticator 解决方案可以工作,但缺点是它首先尝试在没有密码的情况下访问服务器,并且只有在服务器要求输入密码后才提供密码。如果您已经知道服务器需要密码,那将是不必要的往返。

        public class MyStreamHandlerFactory implements URLStreamHandlerFactory {
        
            private final ServerInfo serverInfo;
        
            public MyStreamHandlerFactory(ServerInfo serverInfo) {
                this.serverInfo = serverInfo;
            }
        
            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                switch (protocol) {
                    case "my":
                        return new MyStreamHandler(serverInfo);
                    default:
                        return null;
                }
            }
        
        }
        
        public class MyStreamHandler extends URLStreamHandler {
        
            private final String encodedCredentials;
        
            public MyStreamHandler(ServerInfo serverInfo) {
                String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
                this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
            }
        
            @Override
            protected URLConnection openConnection(URL url) throws IOException {
                String authority = url.getAuthority();
                String protocol = "http";
                URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());
        
                HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
                connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
        
                return connection;
            }
        
        }
        

        这会注册一个新协议 my,在添加凭据时将其替换为 http。因此,在创建新的URLClassLoader 时,只需将http 替换为my,一切都很好。我知道URLClassLoader 提供了一个接受URLStreamHandlerFactory 的构造函数,但如果 URL 指向 jar 文件,则不使用该工厂。

        【讨论】:

          【解决方案10】:

          从 Java 9 开始,您可以这样做

          URL url = new URL("http://www.example.com");
          HttpURLConnection connection = (HttpURLConnection)url.openConnection();
          connection.setAuthenticator(new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication ("USER", "PASS".toCharArray());
              }
          });
          

          【讨论】:

          • 没看到setAuthenticator()方法。
          【解决方案11】:

          我是这样做的,你需要这样做,只需复制粘贴就可以了

              HttpURLConnection urlConnection;
              String url;
           //   String data = json;
              String result = null;
              try {
                  String username ="danish.hussain@gmail.com";
                  String password = "12345678";
          
                  String auth =new String(username + ":" + password);
                  byte[] data1 = auth.getBytes(UTF_8);
                  String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
                  //Connect
                  urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
                  urlConnection.setDoOutput(true);
                  urlConnection.setRequestProperty("Content-Type", "application/json");
                  urlConnection.setRequestProperty("Authorization", "Basic "+base64);
                  urlConnection.setRequestProperty("Accept", "application/json");
                  urlConnection.setRequestMethod("POST");
                  urlConnection.setConnectTimeout(10000);
                  urlConnection.connect();
                  JSONObject obj = new JSONObject();
          
                  obj.put("MobileNumber", "+97333746934");
                  obj.put("EmailAddress", "danish.hussain@mee.com");
                  obj.put("FirstName", "Danish");
                  obj.put("LastName", "Hussain");
                  obj.put("Country", "BH");
                  obj.put("Language", "EN");
                  String data = obj.toString();
                  //Write
                  OutputStream outputStream = urlConnection.getOutputStream();
                  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                  writer.write(data);
                  writer.close();
                  outputStream.close();
                  int responseCode=urlConnection.getResponseCode();
                  if (responseCode == HttpsURLConnection.HTTP_OK) {
                      //Read
                  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
          
                  String line = null;
                  StringBuilder sb = new StringBuilder();
          
                  while ((line = bufferedReader.readLine()) != null) {
                      sb.append(line);
                  }
          
                  bufferedReader.close();
                  result = sb.toString();
          
                  }else {
                  //    return new String("false : "+responseCode);
                  new String("false : "+responseCode);
                  }
          
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          

          【讨论】:

            【解决方案12】:

            ANDROD 实现 从请求用户名和密码授权的 Web 服务请求数据/字符串响应的完整方法

            public static String getData(String uri, String userName, String userPassword) {
                    BufferedReader reader = null;
                    byte[] loginBytes = (userName + ":" + userPassword).getBytes();
            
                    StringBuilder loginBuilder = new StringBuilder()
                            .append("Basic ")
                            .append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
            
                    try {
                        URL url = new URL(uri);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.addRequestProperty("Authorization", loginBuilder.toString());
            
                        StringBuilder sb = new StringBuilder();
                        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line;
                        while ((line = reader.readLine())!= null){
                            sb.append(line);
                            sb.append("\n");
                        }
            
                        return  sb.toString();
            
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    } finally {
                        if (null != reader){
                            try {
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-11-02
              • 2014-07-15
              • 2015-03-28
              • 1970-01-01
              相关资源
              最近更新 更多