苟有恒何必三更眠五更起     最无益莫过一日曝十日寒

java中远程http文件上传及file2multipartfile

    工作中有时会遇到各种需求,你得变着法儿去解决,当然重要的是在什么场景中去完成。

比如Strut2中file类型如何转换成multipartfile类型,找了几天,发现一个变通的方法记录如下(虽然最后没有用上。。):

 1 private static MultipartFile getMulFileByPath(String picPath) {  
 2 
 3         FileItem fileItem = createFileItem(picPath);  
 4 
 5         MultipartFile mfile = new CommonsMultipartFile(fileItem);  
 6 
 7         return mfile;  
 8 
 9     }  
10 
11 
12 
13 private static FileItem createFileItem(String filePath)  
14 
15     {  
16 
17         FileItemFactory factory = new DiskFileItemFactory(16, null);  
18 
19         String textFieldName = "textField";  
20 
21         int num = filePath.lastIndexOf(".");  
22 
23         String extFile = filePath.substring(num);  
24 
25         FileItem item = factory.createItem(textFieldName, "text/plain", true,  
26 
27             "MyFileName" + extFile);  
28 
29         File newfile = new File(filePath);  
30 
31         int bytesRead = 0;  
32 
33         byte[] buffer = new byte[4096];  
34 
35         try  
36 
37         {  
38 
39             FileInputStream fis = new FileInputStream(newfile);  
40 
41             OutputStream os = item.getOutputStream();  
42 
43             while ((bytesRead = fis.read(buffer, 0, 8192))  
44 
45                 != -1)  
46 
47             {  
48 
49                 os.write(buffer, 0, bytesRead);  
50 
51             }  
52 
53             os.close();  
54 
55             fis.close();  
56 
57         }  
58 
59         catch (IOException e)  
60 
61         {  
62 
63             e.printStackTrace();  
64 
65         }  
66 
67         return item;  
68 
69     }  
file2multipartfile

    好不容易写好了一个完整的远程上传方法,并且本地测试已经通过能用,提交后发现有个类实例化不了,debug发现是包不兼容问题(尴尬),

但是以前别人用过的东西,你又不能升级,主要是没权限,不得不去低级的版本中找变通的类似方法,即便方法已经过时了。。

//httpclient(4.5.3)远程传输文件工具类

  1 public static Map<String, String> executeDriverServer(String driverUrl, Map<String, Object> param,String multipart, String contentType,int timeout,String picPath) throws Exception {
  2 
  3         String res = ""; // 请求返回默认的支持json串
  4 
  5         Map<String, String> map = new HashMap<String, String>();
  6                 ContentType ctype = ContentType.create("content-disposition","UTF-8");
  7 
  8         Map<String, String> map = new HashMap<String, String>();
  9 
 10         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
 11 
 12         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
 13 
 14         String res = ""; // 请求返回默认的支持json串
 15 
 16         HttpResponse httpResponse = null;
 17 
 18         try {
 19 
 20             HttpPost httpPost = new HttpPost(driverUrl);
 21 
 22             //设置请求和传输超时时间
 23 
 24             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(5000).build();
 25 
 26             httpPost.setConfig(requestConfig);
 27 
 28             // BTW 4.3版本不设置超时的话,一旦服务器没有响应,等待时间N久(>24小时)。 
 29 
 30             if(httpPost!=null){
 31 
 32                 if("formdata".equals(multipart)){
 33 
 34                     MultipartEntityBuilder mentity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
 35 
 36                     Set<String> keyset = param.keySet();
 37 
 38                     for (String key : keyset) {
 39 
 40                         Object paramObj = Validate.notNull(param.get(key));
 41 
 42                         if(paramObj instanceof MultipartFile) {
 43 
 44                             mentity.addBinaryBody(key, ((MultipartFile) paramObj).getInputStream(),ctype,((MultipartFile) paramObj).getOriginalFilename());
 45 
 46                         }else if(paramObj instanceof File){
 47 
 48                             mentity.addBinaryBody(key, (File)paramObj);//(key, new FileInputStream((File)paramObj),ctype,((File)paramObj).getName());
 49 
 50                         }else{
 51 
 52                             mentity.addPart(key,new StringBody(paramObj.toString(),ctype));
 53 
 54                             //mentity.addTextBody(key,paramObj.toString());
 55 
 56                         }
 57 
 58                         logger.info("key::::"+key);
 59 
 60                         logger.info("paramObj::::"+paramObj.toString());
 61 
 62                     }
 63 
 64                     HttpEntity entity = mentity.build();
 65 
 66                     HttpUriRequest post =  RequestBuilder.post().setUri(driverUrl).setEntity(entity).build();
 67 
 68                     httpResponse = closeableHttpClient.execute(post);
 69 
 70                 }else {
 71 
 72                     HttpEntity entity = convertParam(param, contentType);
 73 
 74                     httpPost.setEntity(entity);
 75 
 76                     httpResponse = closeableHttpClient.execute(httpPost);
 77 
 78                 }
 79 
 80                 if(httpResponse == null) {
 81 
 82                     throw new Exception("无返回结果");
 83 
 84                 }
 85 
 86                 // 获取返回的状态码
 87 
 88                 int status = httpResponse.getStatusLine().getStatusCode();
 89 
 90                 logger.info("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",状态="+status);
 91 
 92                 if(status == HttpStatus.SC_OK){
 93 
 94                     HttpEntity entity2 = httpResponse.getEntity();
 95 
 96                     InputStream ins = entity2.getContent();
 97 
 98                     res = toString(ins);
 99 
100                     ins.close();
101 
102                 }else{
103 
104                     InputStream fis = httpResponse.getEntity().getContent();
105 
106                     Scanner sc = new Scanner(fis);
107 
108                     logger.info("Scanner:::::"+sc.next());
109 
110                     logger.error("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",错误Code:"+status);
111 
112                 }
113 
114                 map.put("code", String.valueOf(status));
115 
116                 map.put("result", res);
117 
118                 logger.info("执行Post方法请求返回的结果 = " + res);
119 
120             }
121 
122         } catch (ClientProtocolException e) {
123 
124             map.put("code", HttpClientUtil.CLIENT_PROTOCOL_EXCEPTION_STATUS);
125 
126             map.put("result", e.getMessage());
127 
128         } catch (UnsupportedEncodingException e) {
129 
130             map.put("code", HttpClientUtil.UNSUPPORTED_ENCODING_EXCEPTION_STATUS);
131 
132             map.put("result", e.getMessage());
133 
134         } catch (IOException e) {
135 
136             map.put("code", HttpClientUtil.IO_EXCEPTION_STATUS);
137 
138             map.put("result", e.getMessage());
139 
140         } finally {
141 
142             try {
143 
144                 closeableHttpClient.close();
145 
146             } catch (IOException e) {
147 
148                 logger.error("调用httpClient出错", e);
149 
150                 throw new Exception("调用httpClient出错", e);
151 
152             }
153 
154         }
155 
156 
157 
158 private static String toString(InputStream in) throws IOException{
159 
160         ByteArrayOutputStream os = new ByteArrayOutputStream();
161 
162         byte[] b = new byte[1024];
163 
164         int len;
165 
166         while((len = in.read(b)) != -1) {
167 
168             os.write(b, 0, len);
169 
170         }
171 
172         return os.toString("UTF-8");
173 
174     }
175 }
4.53包下http远程文件上传

//httpclient(4.2.2)老版本远程传输文件工具类

 1 public static Map<String, String> executeDriverServer(String driverUrl, Map<String, Object> param,String multipart, String contentType,int timeout,String picPath) throws Exception {
 2 
 3         String res = ""; // 请求返回默认的支持json串
 4 
 5         Map<String, String> map = new HashMap<String, String>();
 6 
 7         ContentType ctype = ContentType.create("content-disposition","UTF-8");
 8 
 9         HttpPost httpPost = new HttpPost(driverUrl);
10 
11         MultipartEntity reqEntity = new MultipartEntity();
12 
13         Set<String> keyset = param.keySet();
14 
15         File tempFile = new File(picPath);
16 
17         for (String key : keyset) {
18 
19             Object paramObj = Validate.notNull(param.get(key));
20 
21             if(paramObj instanceof File) {
22 
23                 FileBody fileBody = new FileBody(tempFile);
24 
25                 reqEntity.addPart(key, fileBody);
26 
27             }else{
28 
29                 reqEntity.addPart(key,new StringBody(paramObj.toString()));
30 
31             }
32 
33             logger.info("key::::"+key);
34 
35             logger.info("paramObj::::"+paramObj.toString());
36 
37         }
38 
39         httpPost.setEntity(reqEntity);
40 
41         HttpClient httpClient = new DefaultHttpClient();
42 
43         HttpResponse httpResponse = httpClient.execute(httpPost);
44 
45         // 获取返回的状态码
46 
47         int status = httpResponse.getStatusLine().getStatusCode();
48 
49         logger.info("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",状态="+status);
50 
51         if(status == HttpStatus.SC_OK){
52 
53             HttpEntity entity2 = httpResponse.getEntity();
54 
55             InputStream ins = entity2.getContent();
56 
57             res = toString(ins);
58 
59             ins.close();
60 
61         }else{
62 
63             InputStream fis = httpResponse.getEntity().getContent();
64 
65             Scanner sc = new Scanner(fis);
66 
67             logger.info("Scanner:::::"+sc.next());
68 
69             logger.error("Post请求URL="+driverUrl+",请求的参数="+param.toString()+",请求的格式"+contentType+",错误Code:"+status);
70 
71         }
72 
73         map.put("code", String.valueOf(status));
74 
75         map.put("result", res);
76 
77         logger.info("执行Post方法请求返回的结果 = " + res);
78 
79         return map;
80 
81     }
4.2.2版本http远程传输文件工具类

    希望对大家有点帮助!平常心。

posted @ 2018-07-22 13:55  月魄  阅读(7616)  评论(0编辑  收藏  举报