【问题标题】:Basic Authentication Android API 20基本身份验证 Android API 20
【发布时间】:2014-09-15 07:33:38
【问题描述】:

我无法让基本身份验证在 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


【解决方案1】:

您使用 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);

【讨论】:

  • 当我尝试得到结果时它是空的 httpRequest.connect(); reader = new BufferedReader(new InputStreamReader(httpRequest.getInputStream()));
【解决方案2】:
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】:

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

    希望这对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 2013-03-31
      相关资源
      最近更新 更多