BasicAuth

HelloHttpClientBasicAuthMain

■コード

package hello.org.apache.commons.httpclient;

import java.io.IOException;

import org.apache.commons.httpclient.Credentials;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.HttpMethod;

import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

import org.apache.commons.httpclient.auth.AuthScope;

import org.apache.commons.httpclient.methods.GetMethod;

public class HelloHttpClientBasicAuthMain {

public static void main(String[] args) {

String url = "http://localhost:8080/myweb/hello.html";

HttpClient client = new HttpClient(

new MultiThreadedHttpConnectionManager());

HttpMethod method = new GetMethod(url);

// HTTPClient 初期化

Credentials credentials = new UsernamePasswordCredentials("userid", "password");

AuthScope authscope = new AuthScope("localhost", 8080);


client.getState().setCredentials(authscope, credentials);

client.getParams().setAuthenticationPreemptive(true);

try {

client.executeMethod(method);

byte[] responseBody = method.getResponseBody();

System.out.println(new String(responseBody));

} catch (HttpException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

method.releaseConnection();

client.getHttpConnectionManager().closeIdleConnections(0);

}

}

}