今天在為公司寫網絡硬盤的壓力測試工具時使用了HttpClient,比較容易的解決了登錄、上傳、下載、列表等功能的測試,但也遇到了一些問題,先看看代碼:
1 File f1 = new File("D:\\download\\aa.txt");
2 PostMethod filePost = new PostMethod("http://10.3.3.106:8090/~jid=aWHLXB6y4O9a/webdrive/upload.do?contentID=99999820&action=submit");
3 try{
4 Part[] parts = {new FilePart("file0", f1)};
5 filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
6 }catch(FileNotFoundException e){
7 System.out.println("===================file not found exception: " + e);
8 }
9 HttpClient client = new HttpClient();
10 // 若上傳的文件比較大 , 可在此設置最大的連接超時時間
11 //client.getHttpConnectionManager(). getParams().setConnectionTimeout(5000);
12 int status = 0;
13 try {
14
15 status = client.executeMethod(filePost);
16
17 } catch (HttpException e) {
18 System.out.println("===================http exception: " + e);
19 } catch (IOException e) {
20 System.out.println("===================io exception: " + e);
21 }finally {
22 filePost.releaseConnection();
23 }
24 if (status == HttpStatus.SC_OK) {
25 System.out.println("============================UpLoad file OK! ");
26 }
本來URL中的
contentID和action兩個參數我是通過StringPart來傳遞的,結果傳遞上去的值就成了:
action=Content-Transfer-Encoding: 8bit
submit
而且目前這種方法上傳的文件,也會在文件內容的第一行中出現:Content-Transfer-Encoding: 8bit,由于不影響測試的效果,所以就擱置了,等有空時再來研究這個問題,如果有朋友知道問題的原因,也請一定不要吝嗇您的回答哦。