基本身份验证Android API 20

问题描述 投票:2回答:3

我无法让基本身份验证在HTTP GET上运行。 getCredentialsProvider不存在,然后我环顾四周并尝试了HttpBuilder,但它们也不存在。我运行Android Sdk更新仍然没有运气。我花了三个小时环顾四周,尝试了我发现的每一个,但总有一些部分不存在。

HttpClient httpclient = new DefaultHttpClient();
String username = "User";
String password = "Pass";
Credentials credentials = new UsernamePasswordCredentials(username , password );
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,credentials);

谢谢

android http-get
3个回答
1
投票
Its worked for me.

Authenticator.setDefault(new Authenticator(){
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("xxx","xxx1234".toCharArray());
}});

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(Integer.parseInt(context.getResources().getString(R.string.connection_timeout)));
connection.setUseCaches(false);
connection.connect();
HttpURLConnection httpConnection  =  connection;
int responseCode  =  httpConnection.getResponseCode();
if (responseCode   ==   HttpURLConnection.HTTP_OK) {
    InputStream in  =  httpConnection.getInputStream();
}

3
投票

你使用httpConnection,uri就像http://www.google.com,但正如Kim HJ所说,它真的不安全,所以只能用于测试或高度安全的网络。否则您的凭据是公共域;-)

URL url = new URL(uri);
HttpURLConnection httpRequest = (HttpURLConnection) url.openConnection();
httpRequest.setRequestMethod("GET");
httpRequest.setDoInput(true);
String authString = username + ":" + password;
byte[] authEncBytes = android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
httpsRequest.addRequestProperty("Authorization", "Basic "+ authStringEnc);

1
投票

有两种方法可以进行HTTP基本身份验证:

  1. 添加标题
HttpUriRequest request = new HttpGet(YOUR_URL);
String credentials = YOUR_USERNAME + ":" + YOUR_PASSWORD; 
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", "Basic " + base64EncodedCredentials);
  1. 将凭据添加到凭据提供程序。
defaultHttpClient.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(
                    HTTPS_BASIC_AUTH_USERNAME,
                    HTTPS_BASIC_AUTH_PASWORD));

希望这可能对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.