我无法让基本身份验证在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);
由于
答案 0 :(得分: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 :(得分:1)
有两种方法可以进行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));
希望这对你有所帮助。
答案 2 :(得分: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();
}