Java/HTTP通信/Jakarta Commons HttpClient

Java/HTTP通信/Jakarta Commons HttpClient

バージョンと製造年月日

  • 2012-01-17
  • HttpClient 4.1.2

ライブラリ

現在のところ普通にHTTP通信の実装をするならば Jakarta Commons HttpClient を使うのが普通みたいだ

バージョン違いによりインタフェースが異なるので注意 3系と4系じゃ違う

ファイルをPOSTしてみる

maven

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2.1</version>
</dependency>        
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.1</version>
</dependency>  
DefaultHttpClient httpClient = new DefaultHttpClient();
//POST先をセット
HttpPost method = new HttpPost("http://hoge.jp/piyo");
MultipartEntity entity = new MultipartEntity();
File file = new File("/aaa/bbb/ccc/ddd.jpg");
//mimeは適当でくっつける
FileBody fileBody = new FileBody(file,"application/octet-stream","UTF-8");
//partをつける。第一引数にはPOSTされた側でファイル受ける名前をつける
//通常ブラウザからやる場合の input type="file" のname属性の値を設定
FormBodyPart bodyPart = new FormBodyPart("file", fileBody);
//ファイル名をつけとく
bodyPart.addField("filename", file.getName());
entity.addPart(bodyPart);
method.setEntity(entity);
//送信!
HttpResponse response = httpClient.execute(method);

参考サイト

java/http_connection/jakarta_commons_httpclient.txt · 最終更新: 2017-10-24 12:49 by ore