JavaによるHTTPリクエスト時のパラメータの渡し方
Contents

  1. GET の場合
  2. POST の場合

  1. GET の場合

     GET の場合は、

    http://www.heogehoge.com/hoge.html?parameter1=value1&parameter2=value2

    のように、URL の後に ? に続いて パラメータ名=値&パラメータ名=値 の形式で付加します。

    コーディング例

    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import java.lang.*;
    import java.io.*;
    import java.net.*;

    URL url = new URL("http://www.hogehoge.com/hoge.html?parameter1=value1&parameter2=value2");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setDoOutput(true);
    connection.setUseCashes(false);
    connection.setRequestMethod("GET");
    BufferReader bufferReader = new BufferReader(new InputStreamReader(connection.getInputStream(), "JISAutoDetect"));
    String httpSource = new String();
    String str;
    while ( null != ( str = bufferReader.readLine() ) ) {
        httpSource = httpSource + str;
    }
    bufferReader.close();
    connection.disconnect();


  2. POST の場合

     POST の場合は、

    parameter1=value1&parameter2=value2

    のような パラメータ名=値&パラメータ名=値 形式の文字列を OutputStream に出力します。

    コーディング例

    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import java.lang.*;
    import java.io.*;
    import java.net.*;

    URL url = new URL("http://www.hogehoge.com/hoge.html");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setDoOutput(true);
    connection.setUseCashes(false);
    connection.setRequestMethod("POST");
    String parameterString = new String("parameter1=value1&parameter2=value2");
    PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
    printWriter.print(parameterString);
    printWriter.close();

    BufferReader bufferReader = new BufferReader(new InputStreamReader(connection.getInputStream(), "JISAutoDetect"));
    String httpSource = new String();
    String str;
    while ( null != ( str = bufferReader.readLine() ) ) {
        httpSource = httpSource + str;
    }
    bufferReader.close();
    connection.disconnect();