HttpConnectionAuthenticationMain
少し変なコードだが、こんな感じで基本認証に対応できる。
■コード
package hello.java.net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpConnectionAuthenticationMain {
public void helloHttpConnectionAuthentication() throws Exception {
URL url = new URL("http://localhost/");
final String userid = "userid";
final String password = "password";
HttpURLConnection urlConnection = null;
// <send_request>
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(60 * 1000);
urlConnection.setConnectTimeout(60 * 1000);
urlConnection.setRequestMethod("POST");
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setDoOutput(true);
if (userid != null) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userid, password
.toCharArray());
}
});
}
Map<String, List<String>> headers = urlConnection.getHeaderFields();
Iterator<String> it = headers.keySet().iterator();
System.out.println(">>response header");
while (it.hasNext() == true) {
String key = (String) it.next();
System.out.println("header:" + key + "=" + headers.get(key));
}
System.out.println("response code:" + urlConnection.getResponseCode());
System.out.println("response message:"
+ urlConnection.getResponseMessage());
System.out.println(">>body");
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String line = null; while ((line = reader.readLine())!=null) { System.out.println(line); }
reader.close();
urlConnection.disconnect();
}
public static void main(String[] args) throws Exception {
HttpConnectionAuthenticationMain test = new HttpConnectionAuthenticationMain();
test.helloHttpConnectionAuthentication();
}
}