HttpURLConnectionはpostとget要求を送信します。


HttpURLConnectionはpostとget要求を送信します。 
 
最も一般的なHttp要求はgetとpostだけでなく、get要求は静的ページを取得することができ、パラメータをURLの文字列の後に置いてservletに渡すこともでき、postとgetの違いは、postのパラメータはURLの文字列に入れるのではなく、http要求の本文に入れることである。Javaでは、HttpURLConnectionを使用してこの二つの要求を開始することができます。このようなことを知ることは、soapを知るためにも、servletの自動テストコードを作成するためにも大きな助けになります。以下のコードは、HttpURLConnectionを使用してこれらの2つの要求を開始する方法と、パラメータを伝達する方法を簡単に説明する。
package a;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpInvoker {

	public static final String GET_URL = " http://localhost:8080/welcome1 ";

	public static final String POST_URL = " http://localhost:8080/welcome1 ";

	public static void readContentFromGet() throws IOException {
		//   get   URL  ,  URLEncoder.encode             
		String getURL = GET_URL + " ?username= "
				+ URLEncoder.encode(" fat man ", " utf-8 ");
		URL getUrl = new URL(getURL);
		//      URL,    ,URL.openConnection      URL   ,
		//      URLConnection     ,  URL   http,        HttpURLConnection
		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();
		//     ,     get request       connection.getInputStream()         
		//    
		connection.connect();
		//      ,   Reader  
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		System.out.println(" ============================= ");
		System.out.println(" Contents of get request ");
		System.out.println(" ============================= ");
		String lines;
		while ((lines = reader.readLine()) != null) {
			System.out.println(lines);
		}
		reader.close();
		//     
		connection.disconnect();
		System.out.println(" ============================= ");
		System.out.println(" Contents of get request ends ");
		System.out.println(" ============================= ");
	}

	public static void readContentFromPost() throws IOException {
		// Post   url, get          
		URL postUrl = new URL(POST_URL);
		//     
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();
		// Output to the connection. Default is
		// false, set to true because post
		// method must write something to the
		// connection
		//      connection  ,     post  ,     
		// http   ,      true
		connection.setDoOutput(true);
		// Read from the connection. Default is true.
		connection.setDoInput(true);
		// Set the post method. Default is GET
		connection.setRequestMethod(" POST ");
		// Post cannot use caches
		// Post         
		connection.setUseCaches(false);
		// This method takes effects to
		// every instances of this class.
		// URLConnection.setFollowRedirects static   ,      URLConnection  。
		// connection.setFollowRedirects(true);

		// This methods only
		// takes effacts to this
		// instance.
		// URLConnection.setInstanceFollowRedirects      ,        
		connection.setInstanceFollowRedirects(true);
		// Set the content type to urlencoded,
		// because we will write
		// some URL-encoded content to the
		// connection. Settings above must be set before connect!
		//        Content-type,   application/x- www-form-urlencoded 
		//       urlencoded    form  ,                 URLEncoder.encode
		//     
		connection.setRequestProperty(" Content-Type ",
				" application/x-www-form-urlencoded ");
		//   , postUrl.openConnection()          connect    ,
		//      connection.getOutputStream       connect。
		connection.connect();
		DataOutputStream out = new DataOutputStream(connection
				.getOutputStream());
		// The URL-encoded contend
		//   ,       get URL '?'         
		String content = " firstname= "
				+ URLEncoder.encode("       ", " utf-8 ");
		// DataOutputStream.writeBytes      16   unicode   8           
		out.writeBytes(content);

		out.flush();
		out.close(); // flush and close
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		String line;
		System.out.println(" ============================= ");
		System.out.println(" Contents of post request ");
		System.out.println(" ============================= ");
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		System.out.println(" ============================= ");
		System.out.println(" Contents of post request ends ");
		System.out.println(" ============================= ");
		reader.close();
		connection.disconnect();
	}

	/** */
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			readContentFromGet();
			readContentFromPost();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
 
    
上のreadContentFroomGet関数は一つのget要求を生成して、servlet一つのusernameパラメータに伝達して、値は「fat man」です。readContentFroomPost()関数は1つのpost要求を生成して、servletに1つのfirstnameパラメータを伝えて、値は“1つの大きい肥えた人”です。HttpURLConnection.co nnect関数は、実際にはサーバーとのtcp接続を確立しただけで、http要求を実際に送信していません。postであれgetであれ、httpリクエストは実際にHttpURLConnection.get InputStream()という関数の中に正式に発送されます。readContentFroomPost()では、順序は重い中の重さであり、connectオブジェクトのすべての配置(その一山のset関数)は、connect()関数が実行される前に完成されなければならない。OutputStreamに対する書き込み操作は、inputStreamの読み取り操作の前にしなければならない。これらの順序はhttp要求のフォーマットによって決定される。http要求は実際には2つの部分から構成されています。一つはhttpヘッダで、今回のhttp要求に関する配置はすべてhttpヘッダで定義されています。一つは本文contentで、connect関数の中で、HttpURLConnectオブジェクトの配置値によってhttpヘッダが生成されます。httpヘッダに続くのはhttp要求の本文で、本文の内容はoutputStreamで書き込みますが、実際にはoutputStreamは一つのネットワークストリームではなく、せいぜい文字のストリームです。中に書き込んだものはすぐにネットワークに送られず、ストリームが閉じた後、入力の内容によってhttp本文が生成されます。これでhttpが要請したものはもう準備ができました。get InputStream()関数が呼出されると、準備したhttp要求を正式にサーバに送信し、入力ストリームを返して、今回http要求に対するサーバの返信情報を読み取るために使用されます。http要求はget InputStreamの時にすでに発送されていますので(httpヘッダと本文を含む)、get InputStream関数の後にconnectオブジェクトを設定(httpヘッダの情報を修正)したり、outputStreamに書き込んだり(本文を修正)意味がないので、これらの操作を実行すると異常が発生します。