HttpClient(HttpURLConnection)

org.springframework.http.converter.FormHttpMessageConverter

protected String serializeForm(MultiValueMap<String, Object> formData, Charset charset) {
	StringBuilder builder = new StringBuilder();
	formData.forEach((name, values) -> {
			if (name == null) {
				Assert.isTrue(CollectionUtils.isEmpty(values), "Null name in form data: " + formData);
				return;
			}
			values.forEach(value -> {
				try {
					if (builder.length() != 0) {
						builder.append('&');
					}
					builder.append(URLEncoder.encode(name, charset.name()));
					if (value != null) {
						builder.append('=');
						builder.append(URLEncoder.encode(String.valueOf(value), charset.name()));
					}
				}
				catch (UnsupportedEncodingException ex) {
					throw new IllegalStateException(ex);
				}
			});
	});

	return builder.toString();
}
package http.client.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/*
 * HTTPリクエスト操作クラス。<br />
 */
public class TestHttpRequest {
	String host = "localhost";
	String encode = "utf-8";

	public TestHttpRequest(String host, String encode) {
		this.host = host;
		this.encode = encode;
	}

	/*
	 * GETリクエスト。<br />
	 * @param uri URI
	 */
	protected TestWebResponse doGet(String uri) throws IOException {
		URL urlObj = new URL("http://" + this.host + uri);
		HttpURLConnection http = (HttpURLConnection) urlObj.openConnection();
		http.setRequestMethod("GET");
		http.connect();
		// 結果を取得
		return getResponse(http, encode);
	}

	/*
	 * POSTリクエスト。<br />
	 * @param uri URI
	 * @param postData POSTするデータ
	 */
	protected TestWebResponse doPost(String uri, Map<?, ?> postData) 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);
		}
		URL urlObj = new URL("http://" + this.host + uri);
		HttpURLConnection http = (HttpURLConnection) urlObj.openConnection();
		http.setRequestMethod("POST");
		http.setDoOutput(true);
		http.setRequestProperty("Accept-Language", "ja");
		http.setRequestProperty("Content-Type", "text/html; charset=" + encode);
		// リスエストの送信
		OutputStream os = http.getOutputStream();
		PrintStream ps = new PrintStream(os);
		// データをPOSTする
		ps.print(sbParam.toString());
		ps.close();
		// レスポンスの取得
		return getResponse(http, encode);
	}

	/*
	 * レスポンスデータを取得する。<br />
	 * @param http http接続オブジェクト
	 * @param webEncode エンコーディング
	 */
	private TestWebResponse getResponse(HttpURLConnection http, String webEncode) throws IOException {
		TestWebResponse response = new TestWebResponse();
		// ステータスコードの取得
		response.setStatus(http.getResponseCode());
		// ヘッダの取得
		LinkedHashMap<String, String> resHeader = new LinkedHashMap<String, String>();
		Map<String, List<String>> header = http.getHeaderFields();
		Iterator<String> headerIt = header.keySet().iterator();
		while (headerIt.hasNext()) {
			String key = headerIt.next();
			List<String> valList = header.get(key);
			if (key != null) {
				StringBuilder sb = new StringBuilder();
				for (String val : valList) {
					if (sb.length() > 0)
						sb.append("\n");
					sb.append(val);
				}
				resHeader.put(key, sb.toString());
			}
		}
		response.setHeader(resHeader);
		// ボディ(コンテンツ)の取得
		InputStream is = http.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, webEncode));
		StringBuilder sbBody = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null) {
			sbBody.append(line);
			sbBody.append("\n");
		}
		response.setBody(sbBody.toString());
		return response;
	}
}
package http.client.example;

import java.util.LinkedHashMap;
public class TestWebResponse {
    private int                              status  = 0;
    private LinkedHashMap<String, String>    header  = new LinkedHashMap<String, String>();
    private String                           body    = "";
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public LinkedHashMap<String, String> getHeader() {
        return header;
    }
    public void setHeader(LinkedHashMap<String, String> header) {
        this.header = header;
    }
    public String getBody() {
        return body;
    }
    public void setBody(String body) {
        this.body = body;
    }
}
スポンサーリンク
google 6948682462
google 6948682462

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

スポンサーリンク
google 6948682462