views:

57

answers:

1

enter code hereHi,

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("/","");
  }

  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."); 
 }

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).

+1  A: 

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.

jarnbjo
Yep, that does the trick, and O have to remove the line conn.setFixedLengthStreamingMode(data.length);
Maarten
Hm, too soon.... What happens is that now the client authenticates properly, but data never get sent from the underlying outputstream (I flush after ever write). Basically, I just want to set the Authenticator, connect, get the outputstream and write my data. So I need to get a reference to the inputstream (why isn't this handled in setting u the connection....), but what more.This should be a few lines - what's the use of a standard class library otherwise (sorry about the rant...)
Maarten
More specifically: I have to call conn.getInputStream() to have the proper authentication (I see this on the server waiting, for the uploaded data). It *looks* like that call never returns, even a println after getting the inputstream is not reached
Maarten