【问题标题】:Java HTTP PUT with Digest authentication in JavaJava HTTP PUT 与 Java 中的摘要式身份验证
【发布时间】:2010-09-23 09:45:37
【问题描述】:

我正在尝试使用 PUT 上传带有 Java 的文件,服务器执行摘要式身份验证。我想保持精简,所以我尝试使用 HttpURLConnection.

public void putData(String path, byte [] data) throws IOException, MalformedURLException {

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

  debug("Default authenticator set");
  //Safeguard against double slashes
  if (path.startsWith("/")) {
   path = path.replaceFirst("/","");
  }

  debug(hostname + path);
  URL url = new URL(hostname + path);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  debug("HttpURLConnection acquired");
  conn.setDoOutput(true);
        conn.setDoInput(true);

  conn.setRequestMethod("PUT");
  conn.setRequestProperty("Content-Length",String.valueOf(data.length));
  conn.setRequestProperty("Content-type","application/binary");
  conn.setFixedLengthStreamingMode(data.length);
  conn.connect();

  debug("Properties set");
  OutputStream out = conn.getOutputStream();
  debug("Outputstrem acquired");
  out.write(data,0,data.length);
  out.flush();
  out.close();
  debug("Data written, stream closed."); 
 }

由于某种原因,这无可救药地失败了:我看到 401 又回来了,然后它就完成了。如果我禁用授权,则相同的代码可以工作。使用摘要身份验证下载具有类似代码的文件“正常工作”。有任何想法吗?我真的不想开始使用下一个这么多库,比如来自 Apache 的 htclient 左右(......现在是 2010 年......你会期望带有摘要 authN 的 http 请求可以在任何标准库中工作)。

【问题讨论】:

    标签: java http authentication httpwebrequest digest


    【解决方案1】:

    您至少应该在方法结束时尝试conn.getInputStream(),以强制评估服务器响应。否则,将无法正确检测到来自服务器的潜在错误消息。

    【讨论】:

    • 是的,这就是诀窍,O 必须删除 conn.setFixedLengthStreamingMode(data.length);
    • 嗯,太快了.... 发生的情况是,现在客户端正确地进行了身份验证,但数据永远不会从底层输出流中发送(我写完后刷新)。基本上,我只想设置 Authenticator,连接,获取输出流并写入我的数据。所以我需要获取对输入流的引用(为什么在设置你的连接时不处理这个......),但还有更多。这应该是几行 - 否则标准类库有什么用(抱歉咆哮......)
    • 更具体地说:我必须调用 conn.getInputStream() 以获得正确的身份验证(我在服务器上看到这个等待上传的数据)。 看起来该调用永远不会返回,即使在获取输入流后没有达到 println
    猜你喜欢
    • 2023-03-06
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多