使用httpclient上传文件
2016-01-07 17:22
393 查看
import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.nio.charset.Charset; public class TestSendFile { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080/kafka-api/upload"); FileBody bin = new FileBody(new File(args[0]),ContentType.create("text/plain", Consts.UTF_8)); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); StringBody pk = new StringBody("hupu_bbs", ContentType.create("text/plain", Consts.UTF_8)); StringBody topic = new StringBody("hupu_bbs_index_full", ContentType.create("text/plain", Consts.UTF_8)); HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)//设置浏览器兼容模式,解决文件名乱码问题 .addPart("bin", bin) .addPart("comment", comment) .addPart("pk", pk) .addPart("topic", topic) .setCharset(Charset.forName("utf-8")) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } } }
服务端接收请求:
@RequestMapping("/upload") public Object upload(@RequestParam(value = PUBLIC_SECRET_KEY_FIELD) String pk, @RequestParam(value = TOPIC_FIELD) String topic, HttpServletRequest request) throws IOException { // public String upload(HttpServletRequest request) throws IOException { System.out.println("====================" + pk + "," + topic + "==================="); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; ConfigurableWebApplicationContext context = (ConfigurableWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); final MessageChannel channel = context.getBean(topic + "_Channel", MessageChannel.class); Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null) { LineIterator lineIterator = IOUtils.lineIterator(file.getInputStream(),"utf-8"); while (lineIterator.hasNext()){ String line = lineIterator.next(); System.out.println(line); channel.send(MessageBuilder.withPayload(line).setHeader(KafkaHeaders.MESSAGE_KEY, pk + "|" + rand.nextInt(24)).setHeader(KafkaHeaders.TOPIC, topic).build()); } lineIterator.close(); // String fileName = file.getOriginalFilename(); // String path1 = Thread.currentThread() // .getContextClassLoader().getResource("").getPath() // + "download" + File.separator; // // // 下面的加的日期是为了防止上传的名字一样 // String path = path1 // + new SimpleDateFormat("yyyyMMddHHmmss") // .format(new Date()) + fileName; // // File localFile = new File(path); // Files.createParentDirs(localFile); // file.transferTo(localFile); } } Map<String, Object> map = new HashMap<String, Object>(); map.put("resultCode", "00"); map.put("description", "操作成功"); return map; }
StringBody部分参数可以在服务端通过@RequestParam方式获取。
必须配置如下Bean,否则不能解析文件上传请求:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name="defaultEncoding" value="utf-8" /> <!--1024*200即200k--> <property name="maxUploadSize" value="204800"/> <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常--> <property name="resolveLazily" value="true"/> <property name="maxUploadSizePerFile" value="204800"/> </bean>
相关文章推荐
- AssetsLibrary从网上下载图片,保存到相册,保存网络图片,
- nginx HTTP Upstream模块
- 使用ASIHTTPRequest 编译提示找不到"libxml/HTMLparser.h"的解决方法
- android BroadcastReceiver动态监听网络连接
- TCP滑动窗口机制
- 一次tcp连接被reset的异常故障排查
- HTTP状态码总结
- 网络编程 java
- iOS9请求出现App Transport ... cleartext HTTP (http://)---HTTPS改HTTP
- mac下搭建http服务器(apache+php)并实现上传功能
- http--发送get请求获取网页
- 网络基础原理
- RNN学习笔记(二)-Gradient Analysis
- 转载 注解@PostConstruct与@PreDestroy讲解及实例 - 云淡风轻、仅此一抹 - 博客频道 - CSDN.NET http://blog.csdn.net/yaerfeng/art
- 404、500、502等HTTP状态码介绍
- 9.配置zabbix网络发现
- 图像处理与机器视觉网络资源收罗——倾心大放送
- TCP/IP具体解释--nagle算法和TCP_NODELAY
- Android 判断网络连接
- Nginx服务器配置对https的支持