Show TOC

Get Request Using Basic AuthenticationLocate this document in the navigation structure

Use

The following example shows a direct GET request using basic authentication:

            import com.sap.httpclient.HttpClient;
import com.sap.httpclient.HostConfiguration;
import com.sap.httpclient.auth.UserPassCredentials;
import com.sap.httpclient.auth.AuthScope;
import com.sap.httpclient.http.methods.GET;

/**
 * A simple example that uses HttpClient to perform
 *  a direct GET request using Basic Authentication.
 */
public class SimpleExample4 {

        public static void main(String[] args) throws Exception {

                // creating the http client instance
                HttpClient client = new HttpClient();

                // creating the host configuration
                HostConfiguration host = new HostConfiguration("www.verisign.com", 443);

                // setting the proxy to the host configuration
                host.setProxy("proxy", 8080);

                // setting the host configuration to the client
                client.setHostConfiguration(host);

                // creating the authentication scope for realm "realm" 
                // on the host "www.verisign.com"
                AuthScope ourScope = new AuthScope("www.verisign.com", 443, "realm");

                // creating the credentials
                UserPassCredentials userPass = new UserPassCredentials("username",
                                "password");

                // pass our scope and credentials to HttpClient
                client.getState().setCredentials(ourScope, userPass);

                // create a GET method that reads a file over HTTPS, we are assuming
                // that this file requires basic authentication using the
      // realm above.
                GET httpGet = new GET("https://www.verisign.com/products/index.html");

                // Tell the GET method to automatically handle authentication. 
                // The method will use any appropriate
                // credentials to handle basic authentication requests. 
                // Setting this value to false will cause
                // any request for authentication to return with a status of 401.
                // It will then be up to the client to handle the authentication.
                httpGet.setDoAuthentication(true);

                try {
                        // execute the http method
                        int status = client.executeMethod(httpGet);
                        // showing the response
                        System.out.println("RESPONSE  : ");
                        System.out.println(httpGet.getResponseBodyAsString());
                } finally { // we wont use the connection any more so we release it
                        httpGet.releaseConnection();
                }
        }
}