or1ko's diary

日々を書きます

ユーザ認証があるプロキシのHTTPクライアント

Javaでプロキシを使うHTTPクライアントについて下記が参考になる。
JavaのHTTP通信でプロキシを使う

ユーザの認証がプロキシにある場合は、下記の通り。

  • java.net.Proxyではできない模様。調べたが見つからなかった。
  • システムプロパティで指定はできる。java.net.Authenticatorを利用するらしい。

Authenticated HTTP proxy with Java - Stack Overflow

Apache Commons HTTP Componentsではユーザ指定ができる。
HttpClient - HttpClient Authentication Guide

HTTP クライアント GETの例

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class SampleGetHttpClient {

	public static void main(String[] args) throws IOException {
		String url = "http://localhost:8080/";
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                // HTTPSの場合はHttpsURLConnectionにキャストすれば良いらしい
		connection.setRequestMethod("GET");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			System.out.println(builder);
		}
	}
}

キーと値の設定(ファイル)の読み書き

キーと値だけの設定(ファイル)であれば、
java.uti.Propertiesクラスで簡単に作成できる。
XMLでも入出力できるようになっている。
日本語を含む場合、XMLで出力しておけば、エディタで開いても値がわかる。

import java.io.IOException;
import java.util.Properties;


public class SamplePropertiesIO {

	public static void main(String[] args) throws IOException {
		Properties properties = new Properties();
		properties.setProperty("key", "value");
		properties.store(System.out, "Settings");

		// 読み込む場合は、loadを呼ぶ
		// Properties p2 = new Properties();
		// p2.load(stream);
	}
}

実行結果。

#Settings
#Sun Mar 15 21:02:42 JST 2015
key=value

HTTP サーバの例(POST)

HTTP サーバ。POSTの例。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class PostHttpServer {
	public static void main(String[] args) throws IOException {
		int port = 8080;

		HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
		server.createContext("/", new HttpHandler() {
			@Override
			public void handle(HttpExchange arg0) throws IOException {
				BufferedReader reader = new BufferedReader(new InputStreamReader(arg0.getRequestBody(), StandardCharsets.UTF_8));


				StringBuilder builder = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}

				String s = builder.toString();
				arg0.sendResponseHeaders(200, s.length());
				BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(arg0.getResponseBody(), StandardCharsets.UTF_8));
				writer.write(s);
				writer.flush();
			}
		});
		server.start();

		System.out.println("hit any key");
		System.in.read();
		server.stop(0);
	}
}

HTTPクライアント POSTの例

http://localhost:8080にPOSTでアクセスして、
レスポンスをUTF-8エンコーディングしてコンソールに表示する。

public class SamplePostHttpClient {

	public static void main(String[] args) throws IOException {
		String url = "http://localhost:8080/";
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                // HTTPSの場合、HttpsUrlConnectionにキャストすれば良い
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);

		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
		writer.write("Hello World");
		writer.flush();

		try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			System.out.println(builder);
		}
	}
}

HTTP サーバのGETの例

単純にHello Worldを表示する例。
起動し、http://localhost:8080/にアクセスすると表示される。

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HelloWorldServer {
	public static void main(String[] args) throws IOException {
		int port = 8080;

		HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
		server.createContext("/", new HttpHandler() {
			@Override
			public void handle(HttpExchange arg0) throws IOException {
				String str = "Hello World";
				arg0.sendResponseHeaders(200, str.length());
				OutputStream body = arg0.getResponseBody();
				body.write(str.getBytes());
			}
		});
		server.start();

		System.out.println("hit any key");
		System.in.read();
		server.stop(0);
	}
}