开发者

Java HTTP PUT with Digest authentication in Java

I am trying to upload a file with Java using PUT, server does Digest authentication. I want to keep it lean, so I try to use 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("/","");
  }

  de开发者_如何学Pythonbug(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."); 
 }

For some reason, this fails hopelessly: I see a 401 coming back, and then it's done. If I disable authorization, same code works. Downloading a file with similar code using digest authentication "just works". Any ideas? I'd really rather not start using the next so many libraries like htclient from Apache or so (...it's 2010... you'd expect http requests with digest authN to work in any standard library).


You should at least try conn.getInputStream() at the end of your method, to force evaluation of the server response. Otherwise, potential error messages from the server will not be detected properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜