httpclient 上传图片
Posted yrjns
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpclient 上传图片相关的知识,希望对你有一定的参考价值。
背景:前端上传图片,后台接收到,转发给第三方系统或文件系统。
jar包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5</version> </dependency>
简易代码:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("file") public class FileController { @RequestMapping(value = "upload") @ResponseBody public void upload(HttpServletRequest request) { try { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile coverFile = multipartRequest.getFile("file"); String url = ""; Map<String,String> textMap = new HashMap<>(); HttpUtil.httpClient(url, textMap, coverFile.getName(), coverFile.getInputStream()); } catch (Exception e) { System.out.println(e); } } }
import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; 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.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class HttpUtil { public static String httpClient(String url,Map<String,String> textMap, String fileName,InputStream inputStream) throws ClientProtocolException, IOException{ HttpClient context = new DefaultHttpClient(); HttpPost post = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); //MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String,String> param : textMap.entrySet()) { builder.addTextBody(param.getKey(),param.getValue(),ContentType.TEXT_PLAIN); } builder.addBinaryBody("file",inputStream,ContentType.MULTIPART_FORM_DATA,fileName); post.setEntity(builder.build()); HttpResponse response = context.execute(post); String re = new String(EntityUtils.toByteArray(response.getEntity())); return re; } }
以上是关于httpclient 上传图片的主要内容,如果未能解决你的问题,请参考以下文章
java 怎么根据httpPost 和httpClient 等,传图片到服务器!