
簡単なGET操作です。
HttpURLConnection con = null;
try {
// リクエスト作成
URL url = new URL("http://localhost:8080/tryjava-dummy-web/echo");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
// レスポンスコード取得
int statusCode = con.getResponseCode();
System.out.println(statusCode + " " + con.getResponseMessage());
if (statusCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusCode=" + statusCode);
}
// レスポンスボディ取得
System.out.println(con.getContentType());
InputStream is = con.getInputStream();
String encoding = getEncoding(con);
String content = IOUtils.toString(is, encoding);
System.out.println(content);
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
} finally {
if (con != null) {
con.disconnect();
}
}
上記コード内で使用している簡易的な文字コード判定処理です。
String getEncoding(HttpURLConnection con) {
String encoding = null;
Matcher matcher = Pattern.compile("charset=(.*)", Pattern.CASE_INSENSITIVE).matcher(con.getContentType());
if (matcher.find()) {
encoding = matcher.group(1);
}
System.out.println("encoding=" + encoding);
return encoding;
}
少し複雑なGETです。
HttpURLConnection con = null;
try {
// リクエスト作成
URL url = new URL("http://localhost:8080/tryjava-dummy-web/echo" //
+ "?param1=value1" //
+ "&UrlEncode=" + URLEncoder.encode("+-/_", "UTF-8"));
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
// リダイレクト許可
con.setInstanceFollowRedirects(true);
// キャッシュ設定
con.setUseCaches(true);
// タイムアウト設定(ミリ秒単位)
// ※Java5から使用可能。
con.setConnectTimeout(60 * 1000);
con.setReadTimeout(60 * 1000);
// ヘッダー設定
con.setRequestProperty("Accept-Language", "ja");
con.setRequestProperty("X-Header1", "value1");
// 接続
con.connect();
// レスポンスコード取得
int statusCode = con.getResponseCode();
System.out.println(statusCode + " " + con.getResponseMessage());
if (statusCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusCode=" + statusCode);
}
// レスポンスヘッダ取得
con.getHeaderFields().forEach((key, values) -> {
System.out.println(key + ": " + ToStringBuilder.reflectionToString(values, ToStringStyle.SIMPLE_STYLE));
});
// レスポンスボディ取得
System.out.println(con.getContentType());
InputStream is = con.getInputStream();
String encoding = getEncoding(con);
String content = IOUtils.toString(is, encoding);
System.out.println(content);
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
} finally {
if (con != null) {
con.disconnect();
}
}
POSTリクエストです。レスポンス受信は、GETの時と同じ。
// リクエスト作成
URL url = new URL("http://localhost:8080/tryjava-dummy-web/echo");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
// POSTパラメータ
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), "UTF-8"));
w.write("param1=value1");
w.write("&UrlEncode=" + URLEncoder.encode("+-/_", "UTF-8"));
w.write("&text=" + URLEncoder.encode("日本語", "UTF-8"));
w.flush();
プロキシを使う場合は、事前に次の処理をしておきます。
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", PROXY_HOST);
System.setProperty("proxyPort", String.valueOf(PROXY_PORT));
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(PROXY_USER, PROXY_PASSWORD.toCharArray());
}
});
// この後、HttpURLConnection作成して、HTTP通信を行う。
参考
Apache Commons HttpCientは、Java1.4で使用可能。 Java5以降が使えるなら、Apache HttpComponents HttpClientを使用したほうが良い。
簡単なGETです。
// クライアント作成
HttpClient client = new HttpClient();
// リクエスト作成
HttpMethod method = new GetMethod("http://localhost:8080/tryjava-dummy-web/echo");
try {
// 接続
int statusCode = client.executeMethod(method);
System.out.println("statusCode=" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusCode=" + statusCode);
}
// レスポンスボディ取得
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody, "UTF-8"));
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
} finally {
method.releaseConnection();
}
少し複雑なGETです。
// クライアント作成
HttpClient client = new HttpClient();
try {
// リクエスト作成
HttpMethod method = new GetMethod("http://localhost:8080/tryjava-dummy-web/echo");
// クエリ―文字列は、URLエンコードされる。
// UTF-8以外を使いたいときは、EncodingUtilを使うらしい。
method.setQueryString(new NameValuePair[] { //
new NameValuePair("param1", "value1"), //
new NameValuePair("UrlEncode", "+-/_"), //
new NameValuePair("text", "日本語"), //
});
// ヘッダー設定
method.addRequestHeader("Accept-Language", "ja");
method.addRequestHeader("X-Header1", "value1");
try {
// 接続
int statusCode = client.executeMethod(method);
System.out.println("statusCode=" + statusCode);
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusCode=" + statusCode);
}
// レスポンスヘッダ取得
Header[] headers = method.getResponseHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.print(headers[i]);
}
// レスポンスボディ取得
byte[] responseBody = method.getResponseBody();
System.out.println();
System.out.println(new String(responseBody, "UTF-8"));
} finally {
method.releaseConnection();
}
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
POSTリクエストです。レスポンス受信などは、GETの時と同じ。
// リクエスト作成
PostMethod method = new PostMethod("http://localhost:8080/tryjava-dummy-web/echo");
// POSTパラメータ
// POSTパラメータは、URLエンコードされる。
method.getParams().setContentCharset("UTF-8");
method.setRequestBody(new NameValuePair[] { //
new NameValuePair("param1", "value1"), //
new NameValuePair("UrlEncode", "+-/_"), //
new NameValuePair("text", "日本語"), //
});
// 次の書き方でも良い。
// method.addParameter("param1", "value1");
// method.addParameter("UrlEncode", "+-/_");
// method.addParameter("text", "日本語");
PUTリクエストです。レスポンス受信などは、GETの時と同じ。
// リクエスト作成
PutMethod method = new PutMethod("http://localhost:8080/tryjava-dummy-web/echo");
// パラメータ
method.getParams().setContentCharset("UTF-8");
method.setRequestEntity(new StringRequestEntity("{" //
+ "\"param1\":\"value1\"" //
+ "\"UrlEncode\":\"+-/_\"" //
+ "\"text\":\"日本語\" //" //
+ "}", null, "UTF-8"));
Basic認証のプロキシを使う場合です。
// クライアント作成 HttpClient client = new HttpClient(); // プロキシ設定 client.getHostConfiguration().setProxy(PROXY_HOST, PROXY_PORT); client.getState().setProxyCredentials( // new AuthScope(PROXY_HOST, PROXY_PORT), // new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));
参考
Apache HttpComponents HttpClientは、Java5以上で使用可能。 Apache HttpComponents HttpClient 4.3にて、インターフェース変更あり。
簡単なGETです。
try {
HttpClient client = new DefaultHttpClient();
// リクエスト作成
HttpGet request = new HttpGet("http://localhost:8080/tryjava-dummy-web/echo");
try {
// 接続
HttpResponse response = client.execute(request);
// レスポンスコード取得
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusLine=" + statusLine);
}
// レスポンスボディ取得
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println(content);
} finally {
request.releaseConnection();
}
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
少し複雑なGETです。
try {
HttpClient client = new DefaultHttpClient();
// リクエスト作成
// GETパラメータは、URLエンコードされる。
URIBuilder builder = new URIBuilder("http://localhost:8080/tryjava-dummy-web/echo")
.addParameter("param1", "value1") //
.addParameter("UrlEncode", "+-/_"));
HttpGet request = new HttpGet(builder.build());
request.addHeader("Accept-Language", "ja");
request.addHeader("X-Header1", "value1");
System.out.println(request.getRequestLine());
try {
// 接続
HttpResponse response = client.execute(request);
// レスポンスコード取得
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusLine=" + statusLine);
}
// レスポンスヘッダ取得
for (Header header : response.getAllHeaders()) {
System.out.println(header);
}
// レスポンスボディ取得
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println();
System.out.println(content);
} finally {
request.releaseConnection();
}
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
POSTリクエストです。レスポンス受信などは、GETの時と同じ。
// リクエスト作成
// POSTパラメータは、URLエンコードされる。
HttpPost request = new HttpPost("http://localhost:8080/tryjava-dummy-web/echo");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("UrlEncode", "+-/_"));
params.add(new BasicNameValuePair("text", "日本語"));
request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Basic認証のプロキシを使う場合です。
// クライアント作成 DefaultHttpClient client = new DefaultHttpClient(); // プロキシ設定 HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); client.getCredentialsProvider().setCredentials( // new AuthScope(proxy), // new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));
参考
Apache HttpComponents HttpClientは、Java5以上で使用可能。
簡単なGETです。
// Java7からtry-with-resourcesが使用可能
try (CloseableHttpClient client = HttpClients.createDefault()) {
// リクエスト作成
HttpGet request = new HttpGet("http://localhost:8080/tryjava-dummy-web/echo");
// 接続
// Java7からtry-with-resourcesが使用可能
try (CloseableHttpResponse response = client.execute(request)) {
// レスポンスコード取得
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusLine=" + statusLine);
}
// レスポンスボディ取得
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println(content);
}
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
少し複雑なGETです。
// Java7からtry-with-resourcesが使用可能
try (CloseableHttpClient client = HttpClients.createDefault()) {
// リクエスト作成
// GETパラメータは、URLエンコードされる。
URIBuilder builder = new URIBuilder("http://localhost:8080/tryjava-dummy-web/echo")
.setCharset(Charset.forName("UTF-8")) //
.addParameter("param1", "value1") //
.addParameter("UrlEncode", "+-/_"));
HttpGet request = new HttpGet(builder.build());
request.addHeader("Accept-Language", "ja");
request.addHeader("X-Header1", "value1");
System.out.println(request.getRequestLine());
// 接続
// Java7からtry-with-resourcesが使用可能
try (CloseableHttpResponse response = client.execute(request)) {
// レスポンスコード取得
StatusLine statusLine = response.getStatusLine();
System.out.println(statusLine);
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("エラーレスポンスを受信しました。statusLine=" + statusLine);
}
// レスポンスヘッダ取得
for (Header header : response.getAllHeaders()) {
System.out.println(header);
}
// レスポンスボディ取得
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println();
System.out.println(content);
}
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
POSTリクエストです。レスポンス受信などは、GETの時と同じ。
// リクエスト作成
// POSTパラメータは、URLエンコードされる。
HttpPost request = new HttpPost("http://localhost:8080/tryjava-dummy-web/echo");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("UrlEncode", "+-/_"));
params.add(new BasicNameValuePair("text", "日本語"));
request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Basic認証のプロキシを使う場合です。
// プロキシ設定
HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT);
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials( //
new AuthScope(proxy), //
new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpClientBuilder builder = HttpClients.custom() //
.setDefaultCredentialsProvider(provider) //
.setDefaultRequestConfig(config);
// Java7からtry-with-resourcesが使用可能
try (CloseableHttpClient client = builder.build()) {
// あとは省略。
参考
Apache HttpComponents Fluent APIは、Java5以上で使用可能。
簡単なGETです。
try {
Content content = Request.Get("http://localhost:8080/tryjava-dummy-web/echo").execute().returnContent();
System.out.println(content.asString());
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
簡単なPOSTです。
try {
Content content = Request.Post("http://localhost:8080/tryjava-dummy-web/echo")
.bodyForm(Form.form().add("username", "my-name").add("password", "my-password").build()).execute()
.returnContent();
System.out.println(content.asString());
} catch (Exception e) {
throw new RuntimeException("HTTP通信に失敗しました。", e);
}
Java1.0からの標準APIでURLエンコード/デコードができる。
String encoded = URLEncoder.encode("https://www.tryjava.com/path/name?key1=value1&key2=おはよう#name", "UTF-8");
System.out.println(encoded);
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println(decoded);
[PageInfo]
LastUpdate: 2016-07-03 14:31:08, ModifiedBy: kurukuru-papa
[Permissions]
view:all, edit:admins, delete/config:admins