Android, HttpURLConnection, PUT and Authenticator

3
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")。)
这是为什么?

你解决了这个问题吗? - nilkash
1个回答

2

我无法回答为什么使用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);

试试看。使用基本认证应该已经足够了。


PUT只是一种请求类型。对于Web请求,我通常使用基本身份验证。你这边用不了吗? - dierre
不,还没有。我们无法确定问题出在哪里-我们会继续尝试! - Ken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接