Making a HTTP GET request with HTTP-Basic authentication
Using file_get_contents()
with a stream
to specify the HTTP credentials, or use curl
and the CURLOPT_USERPWD
option.
Angular 6 HTTP Get request with HTTP-Basic authentication
Refer to https://angular.io/guide/http or https://v6.angular.io/guide/http#adding-headers
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('username:password')
})
};
Then use the headers:
return this.http.get<AObjects[]>(this.postsURL, httpOptions);
Make a http request with basic authentication
I use the following in my code to create a default session that include the authentication:
static func defaultURLSession(username : String, password:String) -> NSURLSession {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let userPasswordString = "\(username):\(password)"
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithCarriageReturn)
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
return NSURLSession(configuration: config)
}
HTTP requests with basic authentication
You can use an Authenticator
. For example:
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"user", "password".toCharArray());
}
});
This sets the default Authenticator
and will be used in all requests. Obviously the setup is more involved when you don't need credentials for all requests or a number of different credentials, maybe on different threads.
Alternatively you can use a DefaultHttpClient
where a GET request with basic HTTP authentication would look similar to:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://foo.com/bar");
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("user", "password"),
"UTF-8", false));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity responseEntity = httpResponse.getEntity();
// read the stream returned by responseEntity.getContent()
I recommend using the latter because it gives you a lot more control (e.g. method, headers, timeouts, etc.) over your request.
Http request with basic auth java
Check this. It worked for me.
try {
String webPage = "http://192.168.1.1";
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
How do I use HTTP Basic Auth with http-client?
(define user "user")
(define pass "pass")
(determine-username/password
(lambda (uri realm)
(values user pass)))
See https://wiki.call-cc.org/eggref/5/http-client#authentication-support for the technical details.
Related Topics
How to Remove Empty Paragraph Tags from String
Best Way to Autoload Classes in PHP
Facebook API/PHP - How to Change a User's Profile Image via Fb Graph API
How to Set a Maximum Size Limit to PHP Curl Downloads
How to Set Session Timeout in Laravel
Is There an Equivalent in C++ of PHP's Explode() Function
Object of Class Stdclass Could Not Be Converted to String
Convert Array of Paths into Ul List
How to Catch an Error Caused by Mail()
Php: How to Capture Browser Window Screen with PHP
Curl Requires Curlopt_Ssl_Verifypeer=False
PHP - Time Remaining Until Specific Time from Current Time of Page Load
What Is a Good Method to Sanitize the Whole $_Post Array in PHP
Retrieving the Last Inserted Ids for Multiple Rows