4月 8th, 2008at 10:29

Tags:

HttpClient2.0でダミークライアントを作ってみる

このエントリーをはてなブックマークに追加

HttpClientのサイトがHttpComponentsってサイトになってますね。

HTTPプロトコルを使ってアクセスするのはブラウザが簡単なんだけど、

  • ヘッダ部にこういう情報入れたい
  • body部にCSVとかXMLを入れたい

ときとかにブラウザだとしんどい。

そこで、HttpClientをつかって擬似クライアントを作ってみる。

今回の仕様 

  • 送信先、送信対象ファイル置き場は引数で指定する。
  • 指定したディレクトリにあるファイルをHTTPのBodyに設定して送信する。
  • リクエストはファイル1に対して1送信される。
  • レスポンスはファイルで出力される。

DummyClientクラス 

アクセッサなどは省略してます。

/** * ダミークライアント *  * @author Dai Fujihara *  * 2005/12/20 16:34:29 */public class DummyClient {

 /** HTTPクライアントオブジェクト */ private HttpClient httpClient = new HttpClient();

 /** リクエストするURL */ private String serverURL; /** 読み込むディレクトリ */ private String targetDir; /** 送受信時に使用するエンコード */ private String encode;

 /**  * メイン  * args[0]・・・リクエストするURL  * args[1]・・・読み込むディレクトリ  * args[2]・・・送受信時に使用するエンコード  *   * @param args 引数  */ public static void main(String[] args) {

  DummyClient client = new DummyClient();

  if(args == null || args.length < 2){   System.out.println("DummyClient.main:引数が不正です。      args[0]=リクエストするURL。args[1]=読み込むディレクトリ。      args[2]=エンコード(任意:デフォルトはShift_JIS)");  }

  client.setServerURL(args[0]);  client.setTargetDir(args[1]);

  if(args.length > 2) {   client.setEncode(args[2]);  } else {   client.setEncode("Shift_JIS");  }

  try{   client.execute();  }catch(SystemException e){   System.out.println("DummyClient.main:" + e.getMessage());  }

  System.out.println("DummyClient.main:end."); }

 /**  * コンストラクタ  */ public DummyClient() {}

 /**  * 指定されたディレクトリにあるファイルの数だけHTTPリクエストを送信します。  * 送信時にファイルに書かれた情報をHTTPリクエストのBodyに設定します。  *   * @throws SystemException  */ public void execute() throws SystemException{

  File dir = new File(getTargetDir());  List fileNames = fileNames = IOTool.getFileNames(dir);

  for(int i = 0; i < fileNames.size(); i++){

   String requestFileName = getTargetDir() + "\\" + fileNames.get(i);   String responseFileName = requestFileName;   File requestFile = new File(requestFileName);   File responseFile = new File(responseFileName + ".response.txt");

   try {

    PostMethod postMethod = new PostMethod(getServerURL());    postMethod.setHttp11(true);    postMethod.setRequestHeader("Content-Type", "text/plain; charset=" + getEncode());

    byte[] request = readRequestFromFile(requestFile);    postMethod.setRequestBody(new String(request, getEncode()));

    httpClient.executeMethod(postMethod);

    writeResponseToFile(responseFile, postMethod.getResponseBody());

   } catch (Exception e) {    e.printStackTrace();    throw new SystemException("responseファイル作成に失敗しました。");   }  }

 }

 /**  * ファイル読みこみ  *  * @param aFile requestファイル  * @return ファイルの内容  * @throws IOException 入出力エラー  */ private byte[] readRequestFromFile(File aFile) throws IOException {

  BufferedInputStream bis = null;  ByteArrayOutputStream baos = null;

  try {   bis = new BufferedInputStream(new FileInputStream(aFile));   baos = new ByteArrayOutputStream(512);

   int size = -1;   byte[] buffer = new byte[256];   while ((size = bis.read(buffer, 0, buffer.length)) != -1) {    baos.write(buffer, 0, size);   }  } finally {   if (bis != null) {    bis.close();   }  }

  return baos.toByteArray(); }

 /**  * ファイル書き込み  *  * @param aFile responseファイル  * @param aData ファイルの内容  * @throws IOException 入出力エラー  */ private void writeResponseToFile(File aFile, byte[] aData) throws IOException {

  BufferedOutputStream bos = null;  try {   bos = new BufferedOutputStream(new FileOutputStream(aFile));   bos.write(aData, 0, aData.length);  } finally {   if (bos != null) {    bos.close();   }  } }
  • PostMethodクラスを使うとPostされる
  • PostMethod.setRequestHeaderを利用してヘッダを設定
  • 読み込んだファイルをPostMethod.setRequestBodyで設定
  • HttpClient.executeMethodで送信実行
  • responseはPostMethod.getResponseBodyで取得

出力されるレスポンスファイルはこんな感じになった。
リクエスト先はHTTPリクエストのBodyを取り出して表示してくれるサーブレット

//requestファイルここがBodyにはいってほしいのですわこれが。
//responseファイル <html><head><title>HTTP Confirm</title></head><body><table border='1'><tr> <td>body</td> <td>ここがBodyにはいってほしいのですわこれが。</td></tr></table></body></html>

ちゃんと入ってますね。

このエントリーをはてなブックマークに追加