How to add BASIC Authentication into HttpURLConnection?
Here is one sample.
...
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
...
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = username + ":" + password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+
encodedAuthorization);
...
//Send post data
...
} catch (Exception e) {
...
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
...
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(14923)
- What is runtime polymorphism in Java?(9389)
- What is String literal pool?(8735)
- Can the run() method be called directly to start a thread?(8193)
- How to add BASIC Authentication into HttpURLConnection?(7444)
- Can transient variables be declared as 'final' or 'static'?(6271)
- Can static methods be overridden?(4927)
Most Recent java Faqs
- What is the difference between an enum type and java.lang.Enum?
- Which replace function works with regex?
- Why does TreeSet.add throw ClassCastException?
- What is variable hiding and shadowing?
- Can private method be overridden?
- How to enable JDBC tracing?
- How to Retrieve Automatically Generated Keys in JDBC?