One common task that we have to face during the development is to make an http client.
Sometimes we don’t make only http request via get or post method, but we also have to authenticate request to retrive data.
One type of common authentication that we can run into is Apache Basic Authentication. This authentication is very simple because it only requires an username and password pair sent in plain text.
DefaultHttpClient is a Java class that allows us to make requests via http get/post with a basic auth. This class is not included in standard Java SDK, but is part of a library package called Apache HttpComponents.
We can get more informations about this package here:
httpd.apache.org/docs/2.0/howto/auth.html.
Below there is an usage example.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
public class HttpAuthRequest
{
public static void main(String[] args)
{
DefaultHttpClient client = null;
try
{
// Set url
URI uri = new URI("http://yourdomain.com/yourpage?yourparamname=yourparamvalue");
client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(uri.getHost(), uri.getPort(),AuthScope.ANY_SCHEME),
new UsernamePasswordCredentials("youruser", "yourpass"));
// Set timeout
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
HttpGet request = new HttpGet(uri);
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 200)
{
InputStream responseIS = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS));
String line = reader.readLine();
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
}
else
{
System.out.println("Resource not available");
}
}
catch (URISyntaxException e)
{
System.out.println(e.getMessage());
}
catch (ClientProtocolException e)
{
System.out.println(e.getMessage());
}
catch (ConnectTimeoutException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
if ( client != null )
{
client.getConnectionManager().shutdown();
}
}
}
}
For this example we must include this jar file:
That’s all!
Have fun!