- Base64 is a straight forward encoding for binary data into readable characters.
- The Java class is the javax.xml.bind.DatatypeConverter, which is part of the XML package (JAXB) and has a method called printBase64Binary() that takes in a byte array and returns a encoded BASE64 string.
- The following is a code snippet that encoding the user name and password for BASIC Authentication for Web applications.
- It combines a user name and corresponding password with “:” as delimiter, and converts it to an byte array that can be feed into the printBase64Binary(). Once the encoded string is ready, just set it as value to the Authorization header.
-
The following code is how to do the encoding and set it as a HTTP header in request to server:
import javax.xml.bind.DatatypeConverter;
String encoding =
DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
urlConn.setRequestProperty("Authorization", "Basic " + encoding);
|
Depending the client library, your API to set the header could be
different. For example, if you use Apache Thrift’s HTTP transport, the
code may look like the following:
import org.apache.thrift.transport.THttpClient;
transport.setCustomHeader("Authorization", "Basic " + encoding);
|
No comments:
Post a Comment