Why is HttpURLConnection not resending PUT content when it retries connection after 401 response?
I've got a bit of a weird issue with HttpURLConnection on Android (API level 7). I'm using basic authentication, set up using the default Authenticator like so:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
I'm making a standard request as follows:
public InputStream put(String type, String name, String xml){
try{
String urlString = this.getURLString(type,name);
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
urlConnection.getOutputStream());
out.write(xml);
out.close();
urlConnection.getInputStream();
urlConnection.disconnect();
return null;
}
catch(Exception e){
Log.e(TAG,e.getMessage());
return urlConnection.getErrorStream();
}
}
A packet trace shows that the content is being sent with the HTTP request. I then receive a 401 Una开发者_开发百科uthorized from the server, and resend the response. This time the credentials are sent as I'd expect, but the content is no longer being sent. It's now a blank PUT request with a Content-Length of 0.
Has anyone seen this before, and how do I fix it?
Thanks, Sean
Have eventually solved this by not using the Authenticator and instead adding the Basic Authorization header manually to the HttpURLConnection.
精彩评论