package net.studyinghttp; import java.io.*; import java.net.*; /** * HTTP クライアントの雛形 */ public class HttpClientTester { /** * HttpURLConnection オブジェクト */ HttpURLConnection uCon; /** * オブジェクト作成と同時にソケット作成 * * @param url リクエストを行うURL */ public HttpClientTester (String url) throws MalformedURLException, ProtocolException, IOException { // URL オブジェクトの生成 URL urlObject = new URL(url); // HttpURLConnection オブジェクトの生成 uCon = (HttpURLConnection)urlObject.openConnection(); } /** * GET リクエストを発行 */ public void doGet () throws ProtocolException, IOException { // リクエストメソッド uCon.setRequestMethod("GET"); // 接続・リクエスト発行 uCon.connect(); } /** * POST リクエストを発行 * * @param message リクエストメッセージ */ public void doPost (String message) throws ProtocolException, IOException { // リクエストメソッド uCon.setRequestMethod("POST"); // メッセージがある場合 setRequestMessage(message); // 接続・リクエスト発行 uCon.connect(); } /** * リクエストメッセージを設定 * * @param message リクエストメッセージ */ void setRequestMessage (String message) throws IOException { // リクエストボディを投げられるようにする uCon.setDoOutput(true); // リクエストボディの MIME は application/x-www-form-urlencoded uCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // リクエストボディの長さ uCon.setRequestProperty("Content-Length", Integer.toString(message.length())); // リクエストメッセージを流し込む出力ストリーム BufferedWriter outer = new BufferedWriter(new OutputStreamWriter(uCon.getOutputStream())); outer.write(message); outer.flush(); outer.close(); } /** * ステータスコードの取得 * * @return 3桁のステータスコード */ public int getStatusCode () throws IOException { return uCon.getResponseCode(); } /** * レスポンスを受け取るためのストリームの取得 * * @return レスポンスを受け取るためのストリーム */ public InputStream getResponseStream () throws IOException { return uCon.getInputStream(); } /** * レスポンスボディを文字列として得る * * @return 文字列としてのレスポンスボディ */ public String getResponseToString () throws IOException { // レスポンスボディを受け取るための入力ストリーム BufferedReader inner = new BufferedReader(new InputStreamReader(getResponseStream())); String response = ""; String line = ""; while ((line = inner.readLine()) != null) { response += line + "\n"; } return response; } /** * 接続の切断 */ public void close () { uCon.disconnect(); } public static void main(String[] args) { try { String myUrl = args[0]; HttpClientTester myClient = new HttpClientTester(myUrl); String myMessage = "MESSAGE=Hello"; myClient.doPost(myMessage); System.out.println(myClient.getStatusCode()); System.out.println(myClient.getResponseToString()); } catch (Exception e) { e.printStackTrace(); } } }