我在 Android 上的 HttpURLConnection(API 级别 7)上遇到了一些奇怪的问题。我正在使用基本身份验证,使用默认身份 validator 进行设置,如下所示:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
我提出标准请求如下:
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();
}
}
数据包跟踪显示内容是通过 HTTP 请求发送的。然后我从服务器收到 401 Unauthorized,并重新发送响应。这次凭据按我的预期发送,但不再发送内容。现在它是一个内容长度为 0 的空白 PUT 请求。
有人以前见过这个问题吗?我该如何解决它?
谢谢, 肖恩
最佳答案
最终通过不使用身份 validator 而是将基本授权 header 手动添加到 HttpURLConnection 解决了这个问题。
关于java - 为什么 HttpURLConnection 在 401 响应后重试连接时不重新发送 PUT 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5416538/