[[Javaメモ]] > JavaでHTTPリクエスト
* JavaでHTTPリクエスト [#kf725940]
#setlinebreak(on)
#mycode{{
package 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 MyHttpRequest {
String webHost = "localhost";
String webEncode = "utf-8";
public MyHttpRequest(String host, String encode){
this.webHost = host;
this.webEncode = encode;
}
/*
* GETリクエスト。<br />
* @param uri URI
*/
protected MyWebResponse doGet(String uri) throws IOException {
URL urlObj = new URL("http://" + this.webHost + uri);
HttpURLConnection http = (HttpURLConnection) urlObj.openConnection();
http.setRequestMethod("GET");
http.connect();
// 結果を取得
return getResponse(http, webEncode);
}
/*
* POSTリクエスト。<br />
* @param uri URI
* @param postData POSTするデータ
*/
protected MyWebResponse 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, webEncode);
val = URLEncoder.encode(val, webEncode);
if (sbParam.length() > 0) {
sbParam.append("&");
}
sbParam.append(key).append("=").append(val);
}
URL urlObj = new URL("http://" + this.webHost + uri);
HttpURLConnection http = (HttpURLConnection) urlObj.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Accept-Language", "ja");
// http.setRequestProperty("Content-Type",
// "text/html; charset="+webEncode);
// //////////////////////////////////////
// リスエストの送信
// //////////////////////////////////////
OutputStream os = http.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.print(sbParam.toString());// データをPOSTする
ps.close();
// //////////////////////////////////////
// レスポンスの取得
// //////////////////////////////////////
return getResponse(http, webEncode);
}
/*
* レスポンスデータを取得する。<br />
* @param http http接続オブジェクト
* @param webEncode エンコーディング
*/
private MyWebResponse getResponse(HttpURLConnection http, String webEncode) throws IOException {
MyWebResponse response = new MyWebResponse();
// ステータスコードの取得
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 s;
while ((s = reader.readLine()) != null) {
sbBody.append(s);
sbBody.append("\n");
}
response.setBody(sbBody.toString());
return response;
}
}
}}
レスポンスデータの退避用クラス
#mycode{{
package example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyWebResponse {
private int status = 0;
private LinkedHashMap<String, String> header = new LinkedHashMap<String, String>();
private String body = "";
private List<Map<String,String>> cookies = null;
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;
}
public List<Map<String,String>> getCookies() {
if (cookies != null) {
return cookies;
}
cookies = new ArrayList<Map<String,String>>();;
Map<String,String> headers = getHeader();
Iterator<String> it = (Iterator<String>) headers.keySet().iterator();
while (it.hasNext()){
String key = it.next();
if ("Set-Cookie".equals(key)) {
String val = headers.get(key).toString();
Matcher m = Pattern.compile("^([a-zA-Z_]+)=([^;]+); path=(.+)$").matcher(val);
if (m.find()){
String cookieKey = m.group(1);
String cookieVal = m.group(2);
String cookiePath = m.group(3);
Map<String, String> cookie = new HashMap<String, String>();
cookie.put("key", cookieKey);
cookie.put("val", cookieVal);
cookie.put("path", cookiePath);
cookies.add(cookie);
}
}
}
return cookies;
}
public String getCookie(String key) {
List<Map<String,String>> cookies = getCookies();
for (Map<String,String> cookie : cookies) {
String cookieKey = (String)cookie.get("key");
if (cookieKey.equals(key)) {
return (String)cookie.get("val");
}
}
return "";
}
}
}}