开发者

Android, HttpURLConnection, PUT and Authenticator

开发者 https://www.devze.com 2023-03-28 16:39 出处:网络
url = new URL(UPLOAD_URL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(\"PUT\");
url = new URL(UPLOAD_URL);

urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("content-type", "application/json");
urlConnection.setFixedLe开发者_如何学JAVAngthStreamingMode(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?


I'm not able to answer to why using Authenticator does not work, but I usually use this approach:

    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);

Try it. Using basic auth should be enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消