使用httpclient-4.5.2以form表单形式上传文件 java

来源:互联网 发布:国家卫生统计网络直报 编辑:程序博客网 时间:2024/06/10 21:12

pom依赖:

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.2</version></dependency>


java代码:

import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.HttpClientBuilder;import org.junit.Test;import com.alibaba.fastjson.JSONObject;import java.io.File;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.MultipartEntity;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.DefaultHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;import org.apache.http.util.CharsetUtils;
public static void sendFile(Integer id, Integer value, String filePath) throws Exception {HttpClient httpClient = HttpClientBuilder.create().build();HttpPost httpPost = new HttpPost(postUrl);//加上该header访问会404,不知道原因...//httpPost.setHeader("Content-Type", "multipart/form-data; boundary=-----ZR8KqAYJyI2jPdddL");FileBody fileBody = new FileBody(new File(filePath));StringBody stringBody = new StringBody("application/text", Charset.defaultCharset());JSONObject json = new JSONObject();json.put("id", item_id.toString());json.put("value", value.toString());StringBody contentBody = new StringBody(json.toJSONString(), Charset.defaultCharset());//以浏览器兼容模式访问,否则就算指定编码格式,中文文件名上传也会乱码HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addPart("file", fileBody).addPart("type", stringBody).addPart("data", contentBody).setCharset(CharsetUtils.get("UTF-8")).build();httpPost.setEntity(reqEntity);HttpResponse response = httpClient.execute(httpPost);if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){HttpEntity entitys = response.getEntity();if (entitys != null) {System.out.println(EntityUtils.toString(entitys));}}httpClient.getConnectionManager().shutdown();}





1 0
原创粉丝点击