异乡客

我一生戎马刀上飘 见过英雄弯下小蛮腰 飞檐走壁能飞多高 我坐船练习水上漂

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

//dopostFile

 1 public class HTTPUtil {
 2 
 3     public static String dopostFile(String uri, Map<String,String> params,Map<String,File> fileMap) {
 4         HttpClient httpclient = new DefaultHttpClient();
 5         String backstr = null;
 6         try {
 7             HttpPost postMethod = new HttpPost(uri);
 8 
 9             MultipartEntity reqEntity = new MultipartEntity();
10             for(String fileKey:fileMap.keySet()){
11                 FileBody  fileBody = new FileBody(fileMap.get(fileKey));
12                 reqEntity.addPart(fileKey,fileBody);
13             }
14             for(String paramKey:params.keySet()){
15                 StringBody comment = new StringBody(params.get(paramKey));
16                 reqEntity.addPart(paramKey,comment);
17             }
18             postMethod.setEntity(reqEntity);
19             //postMethod.setEntity(new U
20             // rlEncodedFormEntity(params, "utf-8")); // 将参数填入POST
21             // Entity中
22 //            postMethod.setHeader("Content-Type",
23 //                    "application/x-www-form-urlencoded; charset=utf-8");
24 
25             HttpResponse response = httpclient.execute(postMethod); // 执行POST方法
26             backstr = EntityUtils.toString(response.getEntity(), "utf-8");
27 
28         }catch (Exception e) {
29             // TODO Auto-generated catch block
30             e.printStackTrace();
31         }
32         return backstr;
33 
34     }
35 
36 }

//上传图片

 1 package testSuite;
 2 
 3 import java.io.File;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 import org.junit.Test;
 7 import com.alibaba.fastjson.JSON;
 8 import Vo.ResVo;
 9 import interfaceTest_1.HTTPUtil;
10 
11 public class PicTest {
12 
13 
14     @Test
15     public void Test (){
16         String username = "FBI";
17         String website = "http://192.168.1.100/123.htm";        
18         Map<String,String> m = new HashMap<String,String>();
19         m.put("username",username);    
20         Map<String,File> fileMap = new HashMap<String,File>();
21         fileMap.put("ImageFile", new File("E:/Users/Luo/Desktop/2.jpg"));
22         String res = HTTPUtil.dopostFile(website,m,fileMap);
23         System.out.println(JSON.toJSONString(m));
24         ResVo resVo = JSON.parseObject(res,ResVo.class);
25         System.out.println(res);
26         org.junit.Assert.assertSame(0, resVo.getResult());    
27         }
28 }

 

posted on 2015-09-10 13:39  cvv54  阅读(215)  评论(0编辑  收藏  举报