■呼び出し
package http.client.example02;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import http.client.example02.HttpClientUtilKai.ConnectTimeoutException;
import http.client.example02.HttpClientUtilKai.ResponseData;
public class HttpClientMain {
public static void main(String[] args) throws Exception {
String host = "192.168.0.11:8080";
String uriUTF8 = "/CardAuthStub/echo";
String uriShiftJIS = "/CardAuthStub/echo_shiftjis";
String uriError = "/CardAuthStub/echoXXX";
String urlStr = "http://" + host + uriShiftJIS;
String requestCharset = "Shift-JIS";
String responseCharset = "UTF-8";
Map<String, String> map = new HashMap<String, String>();
map.put("text", "テスト タロウ");
map.put("sleep", "1000");
String postData = makePostParam(map, requestCharset);
int connectTimeout = 1000;
int readTimeout = 5000;
int retryCount = 1;
int retryInterval = 1000;
ResponseData responseData = null;
for (int i = 0; i<=retryCount; i++) {
try {
if (i !=0) {
System.out.println("retry:[" + i + "/" + retryCount +"]");
System.out.println("sleep start");
Thread.sleep(retryInterval);
System.out.println("sleep end");
}
responseData = HttpClientUtilKai.post(urlStr, postData, connectTimeout, readTimeout,Charset.forName(responseCharset));
break;
} catch (ConnectTimeoutException e) {
System.out.println("ConnectTimeoutException:" + e);
} catch (Exception e ) {
System.out.println("ConnectTimeoutException:" + e);
}
}
System.out.println("HttpStatusCode:" + responseData.getHttpStatusCode());
System.out.println("ContentType:" + responseData.getContentType());
System.out.println("Location:" + responseData.getLocation());
System.out.println("body:" + new String(responseData.getStrings()));
}
private static String makePostParam(Map<?, ?> postData, String encode) throws IOException {
// リスエスト情報の組み立て
Iterator<?> it = postData.keySet().iterator();
StringBuilder sbParam = new StringBuilder();
while (it.hasNext()) {
String key = (String) it.next();
String val = (String) postData.get(key);
key = URLEncoder.encode(key, encode);
val = URLEncoder.encode(val, encode);
if (sbParam.length() > 0) {
sbParam.append("&");
}
sbParam.append(key).append("=").append(val);
}
return sbParam.toString();
}
}
■HttpClient
package http.client.example02;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HttpClientUtilKai {
private static final Log log = LogFactory.getLog(HttpClientUtilKai.class);
public static final int BUFFER_SIZE = 4096;
/** HTTP レスポンスステータスコード(取得できない場合のデフォルト値)*/
public static final int HTTP_STATUS_CODE_CAN_NOT_GET = -1;
public static ResponseData post(String urlStr,
String postData,
int connectTimeout,
int readTimeout,
Charset charset) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
// リダイレクトを自動で許可しない設定
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Connection", "close");
// リクエストのボディ送信を許可する
connection.setDoOutput(true);
try {
connection.connect();
} catch (SocketTimeoutException e) {
throw new ConnectTimeoutException(e);
}
String strings = "";
String contentType = null;
String location = null;
int httpStatusCode = HTTP_STATUS_CODE_CAN_NOT_GET;
try {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
outputStream = connection.getOutputStream();
outputStream.write(postData.getBytes("ISO8859_1"));
} finally {
safetyClose(outputStream);
}
try {
inputStream = connection.getInputStream();
strings = copyToString(inputStream, charset);
contentType = connection.getHeaderField("Content-Type");
location = connection.getHeaderField("Location");
httpStatusCode = connection.getResponseCode();
editHeader(connection);
} finally {
safetyClose(inputStream);
}
} catch (IOException e) {
try {
httpStatusCode = connection.getResponseCode();
} catch (Exception e2) {
httpStatusCode = HTTP_STATUS_CODE_CAN_NOT_GET;
}
// レスポンスコードを取得できた場合
if (HTTP_STATUS_CODE_CAN_NOT_GET != httpStatusCode) {
InputStream errorStream = connection.getErrorStream();
// errorstreamを取得できた場合
if (null != errorStream) {
try {
//TODO
editHeader(connection);
strings = copyToString(errorStream, charset);
contentType = connection.getHeaderField("Content-Type");
// } catch (Exception ex) {
// log.debug("", e);
} finally {
safetyClose(errorStream);
}
}
} else {
throw e;
}
} finally {
connection.disconnect();
}
return new ResponseData(httpStatusCode, contentType, location, strings);
}
private static void editHeader(HttpURLConnection connection) {
Map<String, List<String>> headers = connection.getHeaderFields();
System.out.println("===============================");
System.out.println(headers.toString());
System.out.println("===============================");
Iterator<?> headerIt = headers.keySet().iterator();
String header = null;
while (headerIt.hasNext()) {
String headerKey = (String) headerIt.next();
header += headerKey + ":" + headers.get(headerKey) + "\r\n";
}
System.out.println(header);
}
private static void safetyClose(Closeable c) {
if (null == c) {
return;
}
try {
c.close();
} catch (Exception e) {
log.debug("", e);
}
}
public static class ResponseData {
private int httpStatusCode = -1;
private String contentType = null;
private String location = null;
private String strings = "";
public ResponseData(int httpStatusCode, String contentType, String location, String strings) {
this.httpStatusCode = httpStatusCode;
this.contentType = contentType;
this.location = location;
this.strings = strings;
}
public String getStrings() {
return this.strings;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
public String getContentType() {
return contentType;
}
public String getLocation() {
return location;
}
}
public static class ConnectTimeoutException extends Exception {
private static final long serialVersionUID = 1L;
public ConnectTimeoutException() {
super();
}
public ConnectTimeoutException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ConnectTimeoutException(String message, Throwable cause) {
super(message, cause);
}
public ConnectTimeoutException(String message) {
super(message);
}
public ConnectTimeoutException(Throwable cause) {
super(cause);
}
}
/**
* Copy the contents of the given InputStream into a String.
* <p>Leaves the stream open when done.
* @param in the InputStream to copy from (may be {@code null} or empty)
* @param charset the {@link Charset} to use to decode the bytes
* @return the String that has been copied to (possibly empty)
* @throws IOException in case of I/O errors
*/
public static String copyToString(InputStream in, Charset charset) throws IOException {
if (in == null) {
return "";
}
StringBuilder out = new StringBuilder();
InputStreamReader reader = new InputStreamReader(in, charset);
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = reader.read(buffer)) != -1) {
out.append(buffer, 0, bytesRead);
}
return out.toString();
}
public static String copyToString1(InputStream inputStream, Charset charset) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStreamReader reader = new InputStreamReader(inputStream, charset);
int availableSize = inputStream.available();
byte[] bytes = new byte[availableSize + 1];
while (true) {
int size = inputStream.read(bytes);
if (-1 == size) {
break;
}
byteArrayOutputStream.write(bytes, 0, size);
}
return new String(byteArrayOutputStream.toByteArray());
}
public static String copyToString3(InputStream inputStream, Charset charset) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
StringBuilder sbBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sbBody.append(line);
}
return sbBody.toString();
}
}