ネットワーク

Socket vs HTTP

Socket

メリット カスタム化、通信量が少、高性能、リアルタイム性に向ける、暗号化できる

デメリット 開発量が多い、通信データの変換が必要

HTTP

Socketと逆

システム間の通信手段

Java

★持続的接続にいて

Keep-Aliveモードも参照

Java API(URLConnectionとHttpURLConnection) 持続的接続ができない

try {

URL url = new URL("");

URLConnection conn = url.openConnection(); // 汎用

HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //HTTP

conn.setRequestProperty("User-Agent","xxx");

BufferedReader in =

new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

...

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

Apache API(Jakarta Commons HttpClient) 持続的接続ができる

HttpClient 3.x org.apache.commons.httpclient

HttpClient 4.x org.apache.http.client.HttpClient

Java

★ネットワーク通信関連のAPI

>java.netパッケージ

HttpURLConnection

Socket

ServerSocket

DatagramSocket

DatagramPacket

IntetAddress

URL

UnknownHostException

>javax.net.sslパッケージ

HttpsURLConnection

SSLSocket

SSLServerSocket

SSLContext

TrustManagerFactory

KeyManagerFactory

>org.apache.http.impl.clientパッケージ

DefaultHttpClient

>org.apache.http.client.methodsパッケージ

HttpGet

HttpPost

HttpPut

HttpHead

>org.apache.httpパッケージ

HttpResponse

StatusLine

Header

HeaderElement

NameValuesPair

HttpEntity

★ホストとIPアドレスを取得

InetAddress target = InetAddress.getLocalHost(); // ロカール

InetAddress target = InetAddress.getByName("www.yahoo.co.jp"); // リモート

InetAddress target = InetAddress.getByName("12.456.78.910"); // リモート

InetAddress target[] = InetAddress.getAllByName("www.yahoo.co.jp"); // 複数

String ip = target.getHostAddress();

String host = target.getHostName();

★URLオブジェクト

URL url1 = new URL("http://www.yahoo.co.jp/");

URL url2 = new URL("http", "www.yahoo.co.jp", "/main/index.html");

URL url3 = new URL(url1, "/main/index.html");

URL url = new URL("http://andy@www.yahoo.co.jp:80/index.html?id=xyz#abc");

String protocl = url.getProtocol(); // http

String hostName = url.getHost(); // www.yahoo.co.jp

String portNo = url.getPort(); // 80

String query = url.getQuery(); // id=xyz

String path = url.getPath(); // /index.html

String fileName = url.getFile(); // /index.html?id=xyz

String ref = url.getRef(); // abc

String userInfo = url.getUserInfo(); // andy

String userAuth = url.getAuthority(); // andy@www.yahoo.co.jp:80

★コンテンツ情報を取得

URLConnection urlCon = url.openConnection();

String type = urlCon.getContentType(); // text/html

String size = urlCon.getContentLength(); // 1045

String encode = urlCon.getContentEncoding(); // null

String sendDate = urlCon.getDate(); // 2012/04/16

String exp = urlCon.getExpiration(); // 2012/04/16

String lastMod = urlCon.getLastModified(); // 2012/04/16

★URL文字列をエンコード・デコード

String param = "日本語";

String encode = URLEncoder.encode(param, "UTF-8");

String decode = URLEncoder.decode(encode, "UTF-8");

ルール:

・a-z, A-Z, 0-9, ., -, *, _ はそのまま

・空白⇒+

・以上以外⇒%XX