用httpclient 模仿浏览器把图片上传到服务器,用的是POST请求;
我的需求是先生成文件,然后把文件上传,上传成功后把文件删除.
package com.baic.util;
import java.io.File;
import java.io.IOException;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import java.nio.charset.StandardCharsets;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ebon.framework.util.ConfigUtil;
import com.ebon.framework.util.NullUtil;
/**
* 上传文件到服务器
*
* @author wuyahui
*
*/
public class FileClientUtils {
private static Logger logger = LoggerFactory.getLogger(FileClientUtils.class);
/**
* 上传文件到服务器
* @param inputUrl 文件路径
* @param businessId 文件id
* @return
*/
public static void upload(String inputUrl,String businessId) {
// 上传路径
String httpclientPath = ConfigUtil.getProperty("httpclient_path");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 设置请求路径
HttpPost httpPost = new HttpPost(httpclientPath);
CloseableHttpResponse response = null;
// 响应状态码
int statusCode = 0;
try {
// 读取文件
FileBody bin = new FileBody(new File(inputUrl));
// 设置参数体
StringBody comment = new StringBody(businessId, ContentType.TEXT_PLAIN);
// 设置参数 file 文件流 businessId 文件id
HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("businessId", comment)
.build();
httpPost.setEntity(reqEntity);
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
statusCode = response.getStatusLine().getStatusCode();
System.out.println("HTTPS响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength());
// 主动设置编码,来防止响应乱码
String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
System.out.println("HTTPS响应内容为:" + responseStr);
}
} catch (ParseException | IOException e) {
logger.error("httpclient文件上传", e);
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("httpclient文件上传", e);;
}
}
// 如果上传成功删除文件
if (NullUtil.isNotNull(statusCode)) {
if ("200".equals(statusCode + "")) {
new File(inputUrl).delete();
}
}
}
}