【Java】【REST】JavaでRESTRestクライアントを実装する ~HttpURLConnection を使用した場合 ~

HttpURLConnection を使用した場合

 * 何処からかライブラリを取得する必要はない

サンプル

使用するWebサービス

 * Axis2で自作したサービス(例えば、以下のURLを参考)を起動させて、実行した
http://blogs.yahoo.co.jp/dk521123/31944955.html

RestClientWithHttpURLConnection.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;

public class RestClientWithHttpURLConnection {
   public static void main(String args[]) throws Exception {
      String url = "http://localhost:8080/SampleServerWithAxis2/services/HelloWorld/SayHello?name=mike";
      BufferedReader bufferedReader = null;
      StringBuilder stringBuilder = new StringBuilder();
      String line = null;

      try {
          HttpURLConnection httpURLConnection = 
                (HttpURLConnection)new URL(url).openConnection();
          httpURLConnection.setRequestMethod("GET");

          bufferedReader = new BufferedReader(
                new InputStreamReader(
                      httpURLConnection.getInputStream(), "UTF-8"));

          while ((line = bufferedReader.readLine()) != null) {
             stringBuilder.append(line);
              stringBuilder.append("\r\n");
          }

          System.out.println(stringBuilder.toString());

      } catch (IOException e) {
      } finally {
          IOUtils.closeQuietly(bufferedReader);
      }
   }
}

出力

<ns:SayHelloResponse xmlns:ns="Hello">http://services.demo">Hello mike</ns:return></ns:SayHelloResponse>


関連記事

JavaでRESTRestクライアント を実装する

Axis2 を使用した場合

http://blogs.yahoo.co.jp/dk521123/32790425.html

ライブラリ jersey-client を使用した場合

http://blogs.yahoo.co.jp/dk521123/32824085.html

HttpURLConnection を使用した場合

http://blogs.yahoo.co.jp/dk521123/32936064.html

Apache Commons を使用した場合

http://blogs.yahoo.co.jp/dk521123/32936814.html