![](/img/trans.png)
[英]How to secure Web API for android/ios apps with basic authentication
[英]Basic Authentication Android API 20
我無法在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);
謝謝
您使用的是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);
有兩種執行HTTP基本身份驗證的方法:
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);
defaultHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(
HTTPS_BASIC_AUTH_USERNAME,
HTTPS_BASIC_AUTH_PASWORD));
希望這對您有幫助。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.