HttpClientの使い方まとめ
2465 ワード
public class UploadFile extends ActionSupport {
private static final long serialVersionUID = 1L;
private File file;
private String fileName;
private String ext;
private static final String downloadPath=ServletActionContext.getServletContext().getRealPath("/")+"img";
private String docId;
private String webUrl="http://localhost:8080/MultiMedia/img/";
public String getDocId() {
return docId;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String execute() {
String s = UUID.randomUUID().toString();
docId=s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
try {
String newFileName=docId+"."+ext;
File dirPath = new File(downloadPath);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
System.out.println(downloadPath);
InputStream stream = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(stream);
OutputStream bos = new FileOutputStream(downloadPath+"//"+newFileName);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer))>0) {
bos.write(buffer, 0, len);
}
DBUtil.createDocument(fileName, docId,webUrl+newFileName);
bos.close();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
}
最近、画像をアップロードするwebserviceを提供する小さなプロジェクトが行われました.カスタマーサービス側のアップロード画像はapacheのオープンソースプロジェクトHttpClientと呼ばれています.サーバ側で使用されるstruts 2.HttpClientは、ブラウザをシミュレートしてHttpサーバに要求を送信するコードレベルのHttpクライアントツールです.
詳細については、http://javalover00000.iteye.com/blog/702733を参照してください.
サービス側コード