Android、HttpURLConnection、PUT 和身份验证器
url = new URL(UPLOAD_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("content-type", "application/json");
urlConnection.setFixedLengthStreamingMode(responseJSONArray.toString(2).getBytes("UTF8").length);
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(this.CONNECT_TIMEOUT);
urlConnection.connect();
OutputStream output = urlConnection.getOutputStream();
output.write(responseJSONArray.toString(2).getBytes("UTF8"));
output.close();
我之前也已经设置了身份验证器:
Authenticator.setDefault(new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
}
});
我提供了正确的登录详细信息,但服务器以 401
代码响应。 (不过,类似的 GET 请求也可以工作。)最重要的是,在连接和写入流的过程中不会调用方法 getPasswordAuthentication()
。 (我知道这一点是因为我输入了 Log.v("app", "password here")
。)
这是为什么?
url = new URL(UPLOAD_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("content-type", "application/json");
urlConnection.setFixedLengthStreamingMode(responseJSONArray.toString(2).getBytes("UTF8").length);
urlConnection.setDoInput(false);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(this.CONNECT_TIMEOUT);
urlConnection.connect();
OutputStream output = urlConnection.getOutputStream();
output.write(responseJSONArray.toString(2).getBytes("UTF8"));
output.close();
I've also already earlier set the Authenticator with:
Authenticator.setDefault(new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
}
});
I supply correct login details, but the server responds with a 401
code. (A similar GET-request works though.) On top of which, the method getPasswordAuthentication()
is not being called in the process of connecting and writing to the stream. (I know this because I put in Log.v("app", "password here")
.)
Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法回答为什么使用身份验证器不起作用,但我通常使用这种方法:
尝试一下。使用基本身份验证应该足够了。
I'm not able to answer to why using Authenticator does not work, but I usually use this approach:
Try it. Using basic auth should be enough.