getting error java.io.IOException: Server returned HTTP response code: 401 for

為{幸葍}努か 提交于 2019-11-29 04:29:28

The 401 error code means "Unauthorized". I believe your code does not correctly encode the Authentication header. Assuming the server expects a Basic Access Authentication the code should look like this:

String credentials = "ptt" + ":" + "ptt123";
String encoding = Base64Converter.encode(credentials.getBytes("UTF-8"));
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));

A comprehensive description of the HTTP basic and digest authentication schemes are available in RFC 2617

Another simple way is to use an Authenticator.

From the docs

The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information.

URL url = null;
try {
    url = new URL("YOUR_URL");
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("YOUR_USERNAME","YOUR_PASSWORD".toCharArray());
        }
    });
}catch (MalformedURLException ex) {
        e = new WebServiceException(ex);
}
Arpan24x7

Here you may handle Error code 401. Using HTTPURLCONNECTION here is my code please check you may help this

URL Url = new URL(<your url string>);
HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
connection.setRequestProperty(<your request header);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();

int responseCode = connection.getResponseCode();

if (responseCode == 200) 
    { InputStream is = connection.getInputStream();
      if (is != null) 
         { BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                        response = rd.readLine();
                    }
} else { InputStream is = connection.getErrorStream();

          BufferedReader rd = new BufferedReader(new InputStreamReader(is));

      response = rd.readLine();

} if (response != null)
        AppLog.e("Response-->", response);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!