httpclient 2006/10/25
2006/11/25

javaプログラムから、httpを利用してファイルをアップロードする方法です。

使用するのは、
http://jakarta.apache.org/commons/httpclient/

あと必要なのは、
http://jakarta.apache.org/commons/codec/

実際のコードサンプル

PostMethod post = new PostMethod("http://アドレス");
HttpClient httpclient = new HttpClient();
File file = new File(アップロードファイル);
try {
Part[] parts = { new FilePart("file", file),
new StringPart("key", "xxxxxx") };

post.setRequestEntity(new MultipartRequestEntity(parts,
post.getParams()));
post.setRequestHeader("Content-type", "multipart/form-data;");

int result = httpclient.executeMethod(post);
// resultのコードをみて判断させてもよい 200 404等。
} catch (IOException e) {
e.printStackTrace();
} finally {
post.releaseConnection();
}



参考にさせていただいたサイト commonsの使い方がいろいろまとめられていて勉強になります。


java上から簡単にwebサイトに接続できて便利ですね。

: