最近工作要求不同系统间上传附件,因为两个系统是部署在两台服务器上,就用了http请求来上传附件。
添加的jar包:
<!-- httpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
代码如下:
发起请求的系统:
public static String start(String url,String base64String,String imageFilePath,String path) throws ClientProtocolException, IOException{
// 1. 创建上传需要的元素类型
// 1.1 装载本地上传图片的文件
File imageFile = new File(imageFilePath);
FileBody imageFileBody = new FileBody(imageFile);
// 1.2 装载经过base64编码的图片的数据
String imageBase64Data = base64String;
ByteArrayBody byteArrayBody = null;
if(StringUtils.isNotEmpty(imageBase64Data)){
byte[] byteImage = Base64.decodeBase64(imageBase64Data);
byteArrayBody = new ByteArrayBody(byteImage,"image_name");
}
// utf-8,否则中文会乱码
ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
// 1.3 装载上传字符串的对象
StringBody name = new StringBody("admin", contentType);
StringBody imgpath = new StringBody(path, contentType);
System.out.println("装载数据完成");
MultipartEntityBuilder builder =MultipartEntityBuilder.create()
.addPart("name", name)
.addPart("imgpath",imgpath)
.addPart("file1",imageFileBody)
.addPart("file2",byteArrayBody);
builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
// 2. 将所有需要上传元素打包成HttpEntity对象
HttpEntity reqEntity =builder.build();
System.out.println("打包数据完成");
// 3. 创建HttpPost对象,用于包含信息发送post消息
HttpPost httpPost = new HttpPost(url);
//不添加该头,请求会失败
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
httpPost.setEntity(reqEntity);
System.out.println("创建post请求并装载好打包数据");
// 4. 创建HttpClient对象,传入httpPost执行发送网络请求的动作
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println("发送post请求并获取结果");
// 5. 获取返回的实体内容对象并解析内容
HttpEntity resultEntity = response.getEntity();
String responseMessage = "";
try{
System.out.println("开始解析结果");
if(resultEntity!=null){
InputStream is = resultEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = "";
while((line = br.readLine()) != null){
sb.append(line);
}
responseMessage = sb.toString();
System.out.println("解析完成,解析内容为"+ responseMessage);
}
EntityUtils.consume(resultEntity);
}finally{
if (null != response){
response.close();
}
}
return responseMessage;
}
public static void main(String[]args){
String url = "http://127.0.0.1:8080/khUpload/upload.htm";
//构建http客户端
HttpClient client = new HttpClient();
//构建http post方法
PostMethod post = new PostMethod(url);
//获得http返回码
try {
int returnFlag = client.executeMethod(post);
} catch (IOException e) {
e.printStackTrace();
return -1;//被请求系统服务器不通
}
try {
HttpUtil.start(url,"dfdfdfdf", "E:\imooc\2.jpg","E:\imooc");
} catch (IOException e) {
e.printStackTrace();
}
}
被请求系统:
控制类:
@RequestMapping("/upload")
public String upload(@RequestParam(value = "file1", required = false) MultipartFile file1,
@RequestParam(value = "file2", required = false) MultipartFile file2,
String name,
String imgpath,
HttpServletRequest request) {
String flag = uploadAttachService.upload(file1,file2, imgpath);
return flag;
}
实现类:
public String upload(MultipartFile file1,MultipartFile file2, String path) {
String fileName1 = file1.getOriginalFilename();
String fileExtensionName1 = fileName1.substring(fileName1.lastIndexOf(".") + 1);
String uploadFileName1 = UUID.randomUUID().toString() + "." + fileExtensionName1;
//判断文件上传目录是否存在
File fileUpDir =new File(path);
if(!fileUpDir.exists()&&!fileUpDir.isDirectory()) {
fileUpDir.mkdirs();
}
File targetFile1 = new File(path, uploadFileName1);
try {
file1.transferTo(targetFile1);
return "success";
} catch (IOException e) {
return "false";
}
}
java发送http请求的两种方式:HTTPClient和CloseableHttpClient
参考链接:https://blog.csdn.net/qq_28379809/article/details/82898792