gpt4 book ai didi

java - Android、HttpURLConnection、PUT 和 Authenticator

转载 作者:太空狗 更新时间:2023-10-29 13:39:51 25 4
gpt4 key购买 nike

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 设置为:

Authenticator.setDefault(new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(loginNameString, passwordString.toCharArray());
}
});

我提供了正确的登录详细信息,但服务器以 401 代码响应。 (虽然类似的 GET 请求有效。)最重要的是,在连接和写入流的过程中未调用方法 getPasswordAuthentication()。 (我知道这一点是因为我输入了 Log.v("app", "password here")。)

这是为什么?

最佳答案

我无法回答为什么使用 Authenticator 不起作用,但我通常使用这种方法:

    String webPage = "http://192.168.1.1";
String name = "admin";
String password = "admin";

String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);

尝试一下。使用基本身份验证就足够了。

关于java - Android、HttpURLConnection、PUT 和 Authenticator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7063052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com