HTTP通信
JavaでのHTTP通信
・getInputStream()は中でconnect()を呼び出すため、connect()を明示的に書かなくてもよい
・setXXX()とgetOutputStream()は必ずgetInputStream()の前に行う
Socket版
String host = "localhost";
int port = 8080;
String path = "/WebTest/login";
Socket socket = null;
BufferedReader reader = null;
BufferedWriter writer = null;
try {
// ソケットの作成
socket = new Socket(host, port);
reader =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer =
new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// HTTPリクエスト送信
writer.write("GET " + path + " HTTP/1.1\r\n");
writer.write("Host: " + host + "\r\n");
writer.write("Connection: close\r\n");
writer.write("\r\n");
writer.flush();
// HTTPレスポンス受信(●ヘッダ部+ボディ部)
StringBuilder sb = new StringBuilder();
String line = null;
while( (line = reader.readLine()) != null ){
sb.append(line).append("\n");
}
System.out.println(sb.toString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URLシンプル版
BufferedReader reader = null;
try {
URL url = new URL("http://localhost:8080/WebTest/login");
// HTTPレスポンス受信(ボディのみ)
String line = null;
// ※GETリクエストを発行
reader = new BufferedReader(new InputStreamReader(url.openStream()));
while( (line = reader.readLine()) != null ){
System.out.println(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URLConnection版
BufferedReader reader = null;
try {
String msg = "メッセージ";
msg = URLEncoder.encode(msg, "UTF-8");
URL url = new URL("http://localhost:8080/WebTest/login?msg=" + msg);
URLConnection conn = url.openConnection();
// HTTPリクエスト送信
// ※GET・POSTが設定できない、デフォルト:GET
conn.setRequestProperty("Host","localhost");
conn.setRequestProperty("Connection","close");
// HTTPレスポンス受信
StringBuilder sb = new StringBuilder();
int contentLength = conn.getContentLength();
if(contentLength > 0){
// ●ヘッダ部
System.out.println(conn.getHeaderField("Content-Type")); // 方法1
System.out.println(conn.getContentType()); // 方法2
// ●ボディ部
String line = null;
reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
while( (line = reader.readLine()) != null ){
sb.append(line).append("\n");
}
}
System.out.print(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// ※URLConnectionがclose()とdisconnect()を持たない
}
Apache HttpClient版
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class HttpServerIF {
private static final String TAG = HttpServerIF.class.getSimpleName();
private static final int UNKNOWN_HOST = -1;
private Bitmap resBitmap = null;
private String resText = null;
private HttpClient client = new DefaultHttpClient();
private interface Executable{
void doAction(HttpEntity entity) throws Exception;
}
public Bitmap getResBitmap() {
return resBitmap;
}
public String getResText() {
return resText;
}
public int requestText(String url){
return
this.requestByGet(url, null, new Executable() {
public void doAction(HttpEntity entity) throws Exception {
resText = EntityUtils.toString(entity);
}
});
}
public int requestImage(String url){
return
this.requestByGet(url, null, new Executable() {
public void doAction(HttpEntity entity) throws Exception {
Bitmap bmp =
BitmapFactory.decodeStream(entity.getContent());
if(bmp != null){
resBitmap = bmp;
}
}
});
}
// ★GETの場合
private int requestByGet(String url, Map<String, String> requestParams, Executable exe){
Log.d(TAG, url);
int rtn = UNKNOWN_HOST;
if(requestParams != null){
// リクエストパラメータを設定
StringBuilder builder = new StringBuilder(url);
builder.append("?");
for (Map.Entry<String, String> entry : requestParams.entrySet()) {
builder
.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
url = builder.toString();
url = url.substring(0, url.length() - 1);
}
HttpGet httpGet = new HttpGet(url);
Log.d(TAG, httpGet.getURI().toString());
try {
HttpResponse res = client.execute(httpGet);
rtn = printResponse(res, exe);
} catch (ClientProtocolException e) {
Log.d(TAG, "Exception", e);
} catch (IOException e) {
Log.d(TAG, "Exception", e);
} catch (Exception e) {
Log.d(TAG, "Exception", e);
} finally {
if(httpGet != null){
httpGet.abort();
}
client.getConnectionManager().shutdown();
}
return rtn;
}
// ★POSTの場合
private int requestByPost(String url, Map<String, String> requestParams, Executable exe){
Log.d(TAG, url);
int rtn = UNKNOWN_HOST;
List<NameValuePair> params = null;
if(requestParams != null){
// リクエストパラメータを設定
params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : requestParams.entrySet()) {
params.add(
new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
HttpPost httpPost = new HttpPost(url);
Log.d(TAG, httpPost.getURI().toString());
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse res = client.execute(httpPost);
rtn = printResponse(res, exe);
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "Exception", e);
} catch (ClientProtocolException e) {
Log.d(TAG, "Exception", e);
} catch (IOException e) {
Log.d(TAG, "Exception", e);
} catch (Exception e) {
Log.d(TAG, "Exception", e);
} finally {
if(httpPost != null){
httpPost.abort();
}
client.getConnectionManager().shutdown();
}
return rtn;
}
private int printResponse(HttpResponse res, Executable exe) throws Exception{
int rtn = UNKNOWN_HOST;
if(res != null){
rtn = res.getStatusLine().getStatusCode();
if(rtn == HttpStatus.SC_OK){
// ●ヘッダ部
Header[] headers = res.getAllHeaders();
for (Header header : headers) {
Log.d(TAG, header.getName() + ":" + header.getValue());
}
// ●ボディ部
exe.doAction(res.getEntity());
}
}
return rtn;
}
}
※Androidと連携するコートも含む
HttpURLConnection版 GETの場合
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
String msg = "メッセージ";
msg = URLEncoder.encode(msg, "UTF-8");
URL url = new URL("http://localhost:8080/WebTest/login?msg=" + msg);
conn = (HttpURLConnection)url.openConnection();
// HTTPリクエスト送信
conn.setRequestMethod("GET");
conn.setRequestProperty("Host","localhost");
conn.setRequestProperty("Connection","close");
if( conn.getResponseCode() != HttpURLConnection.HTTP_OK ){
throw new RuntimeException("失敗");
}
// HTTPレスポンス受信
// ●ヘッダ部
System.out.println(conn.getHeaderField("Content-Type"));
// ●ボディ部
StringBuilder sb = new StringBuilder();
String line = null;
reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
while( (line = reader.readLine()) != null ){
sb.append(line).append("\n");
}
System.out.print(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(conn != null){
conn.disconnect();
}
}
HttpURLConnection版 POSTの場合
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
String msg = "\"msg\":\"メッセージ\"";
byte[] data = msg.getBytes("UTF-8");
URL url = new URL("http://localhost:8080/WebTest/login");
conn = (HttpURLConnection) url.openConnection();
// HTTPリクエスト送信
// ●ヘッダ部
conn.setRequestMethod("POST"); // デフォルト:GET
conn.setDoOutput(true); // デフォルト:false POSTの場合に必要
conn.setDoInput(true); // デフォルト:true
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Charset", "UTF-8");
// JSONの場合
//conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// ●ボディ部
msg = URLEncoder.encode(msg, "UTF-8");
msg = URLEncoder.encode(msg, "UTF-8"); // 二回が必要
// 方法1
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write("msg=" + msg + "&id=111");
writer.flush();
writer.close();
// 方法2
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("msg=" + msg + "&id=111");
out.flush();
out.close();
if( conn.getResponseCode() != HttpURLConnection.HTTP_OK ){
throw new RuntimeException("失敗");
}
// HTTPレスポンス受信
StringBuilder sb = new StringBuilder();
String line = null;
reader =
new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(conn != null){
conn.disconnect();
}
}
※サーバ側:String msg = URLDecoder.decode( request.getParameter("msg"), "UTF-8" );
★ファイルをダウンロード
InputStream in = null;
FileOutputStream out = null;
try {
URL url = new URL("http://xxx.com/file.zip");
URLConnection conn = url.openConnection();
in = conn.getInputStream();
File file = new File("C:\\Download\\file.zip"); // 保存先
out = new FileOutputStream(file, false);
byte[] bytes = new byte[512];
int ret;
while( (ret = in.read(bytes)) != 0 ){
out.write(bytes, 0, ret);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
★HTTPヘッダの設定
※staticメソッド
HttpURLConnection.setFollowRedirects(false); //デフォルト:true
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("Referer","http://xxx.com/");
conn.setRequestProperty("Accept-Language","ja");
conn.setRequestProperty("Accept-Encoding","gzip, deflate");
conn.setRequestProperty("User-Agent","Mozilla/4.0 xxx");
conn.setRequestProperty("Host","my.host.com");
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Cookie","ID=1234; name=xxx");
conn.setRequestProperty("Charset", "UTF-8");
●タイムアウト
// JDK 1.5以前
System.setProperty("sun.net.client.defaultConnectTimeout", "5 * 1000");
System.setProperty("sun.net.client.defaultReadTimeout", "5 * 1000");
// JDK 1.5以降
conn.setConnectTimeout(5 * 1000);
conn.setReadTimeout(5 * 1000);
★Proxy経由の手段
●方法1
// Proxyを使うかフラグ
boolean isUseProxy = true;
String proxyHost = "my.proxy.com"; // ドメイン名・IPアドレス
int proxyPort = 8080;
String path = "http://www.google.com";
URL url = isUseProxy ?
new URL("http", proxyHost, proxyPort, path) : new URL(path);
●方法2
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", "my.proxy.com");
System.setProperty("proxyPort", "8080");
●方法3
URL url = new URL("http://www.google.com");
Proxy proxy = new Proxy(
Proxy.Type.HTTP,
new InetSocketAddress("my.proxy.com", 8080));
URLConnection connection = url.openConnection(proxy);
●方法4(Apache HttpClientの場合)
HttpHost proxy = new HttpHost("localhost", 8080);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);