Reputation: 1192
I cannot get the Basic Authentication to work on HTTP GET. The getCredentialsProvider does not exist, then I look around and tried HttpBuilder but that do not exist either. I run the Android Sdk update still no luck. I spend three hours looking around and tried every one I found but there was always some part that didn't exist.
HttpClient httpclient = new DefaultHttpClient();
String username = "User";
String password = "Pass";
Credentials credentials = new UsernamePasswordCredentials(username , password );
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,credentials);
Thanks
Upvotes: 2
Views: 2461
Reputation: 422
There are 2 ways to do HTTP basic authentication:
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));
Hope this might help you.
Upvotes: 1
Reputation: 495
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();
}
Upvotes: 1
Reputation: 53
You use httpConnection, an uri is something like http://www.google.com, but as Kim HJ said, its really insecure, so use it only for testing or in a highly secure network. Otherwise your credentials are public domain ;-)
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);
Upvotes: 3