您的位置:首页 > 理论基础 > 计算机网络

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

2017-01-13 16:52 531 查看
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
4000
.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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息