Java通信APIのまとめ(二)HttpUrlConnectionの使い方


1.はじめに

 今回はHttpUrlConnectionの使い方を簡単にまとめてみます。
 HttpURLconnectionっていうのはhttpを基に、get,post,put,deleteなどのリクエストをサポートすることです。通常get及びpostメソッドをよく使われる。
 だから、本記事もget及びpostメソッドに対して説明します。

2.GETメソッドの使い方

先ずはgetUrlを指定して、getUrlをパラメーターとしてURLクラスのインスタンス
作ってみた。
 connection対象をもらったら、通信を始めてレスポンスコードを戻って、成功したら、入力ストリーム
でデータ情報を読み込。
 

String getUrl = "https://github.com/Hyman1993";
URL url = new URL(getUrl);
//connectionのインスタンス
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//リクエストのメソッドを指定
connection.setRequestMethod("GET");
//通信開始
connection.connect();
// レスポンスコードを戻る
int responseCode = connection.getResponseCode();
// レスポンスコードを判断する、OKであれば、進める
if(responseCode == HttpURLConnection.HTTP_OK){
      // 通信に成功した
      // テキストを取得する
      InputStream in= connection.getInputStream();
      String encoding = con.getContentEncoding();
      if(null == encoding){
          encoding = "UTF-8";
      }
  StringBuffer result = new StringBuffer();
  final InputStreamReader inReader = new InputStreamReader(in, encoding);
  final BufferedReader bufReader = new BufferedReader(inReader);
  String line = null;
  // 1行ずつテキストを読み込む
  while((line = bufReader.readLine()) != null) {
      result.append(line);
  }
  //  クローズ
  bufReader.close();
  inReader.close();
  in.close();
  // アウトプット
  Log.log("result=============:"+result);
}

また、パラメーターを渡す場合、urlを以下のように定義していいです。

String getUrl = "https://github.com/Hyman1993?userName=Hyman1993&password=123456";

3.POSTメソッドの使い方

POSTメソッドについて、一番大切なことはconnectionから出力ストリームをもらってデータ情報をサーバへ書き出す。
  次は例を上げて説明しましょう。

3.1 JSONデータをアップロード

  下記のソースを参考しましょう。

            String postUrl = "https://github.com/Hyman1993";
            URL url = new URL(postUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //POSTに指定
            connection.setRequestMethod("POST");
            //アウトプット可能
            connection.setDoOutput(true);
            //入力可能
            connection.setDoInput(true);
            //cache無し
            connection.setUseCaches(false);
      // データタイプをjsonに指定する
      connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //コネクション、通信開始
            connection.connect();
            // jsonデータを出力ストリームへ書き出す
       String body = "userName=hyman1993&password=123456";
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            writer.write(body);
            writer.close();

            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                      // 通信に成功した
              // GETメソッドを同様に
            }

3.2 ファイルをアップロード

    String postUrl = "https://github.com/Hyman1993";
    URL url = new URL(postUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type", "file/*");
    connection.connect();

    OutputStream outputStream = connection.getOutputStream();
    FileInputStream fileInputStream = new FileInputStream("file");
    int length = -1;
    byte[] bytes = new byte[1024];
    while ((length = fileInputStream.read(bytes)) != -1){
        outputStream.write(bytes,0,length);
    }
    fileInputStream.close();
    outputStream.close();

    int responseCode = connection.getResponseCode();
    if(responseCode == HttpURLConnection.HTTP_OK){
                 // 通信に成功した
                 // GETメソッドを同様に
    }

最後に

最後まで読んでいただき、ありがとうございます。
今度はSocketChannelの使い方をまとめる予定です。