版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_17522211/article/details/84662316
pom.xml:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>
发送端:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
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.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
public class PostTest {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("url");// 请求地址
MultipartEntityBuilder meb = MultipartEntityBuilder.create();
ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
meb.addBinaryBody("uploadfile", new File("D://123.txt"));// 需要传输的文件,参数也可以是流
meb.addTextBody("param1", "paramvalue", strContent);// 普通字段,指定编码
meb.addTextBody("param2", "paramvalue", strContent);// 普通字段,指定编码
HttpEntity httpEntity = meb.build();
httpPost.setEntity(httpEntity);
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收端:
@RequestMapping(value = "/emailattach", produces = "application/json; charset=utf-8")
@ResponseBody
public String email(
@RequestParam("uploadfile")MultipartFile file,
@RequestParam("param1")String param1,
@RequestParam("param2")String param2
) {
log.info("receive_param1-{},param2:{}",param1,param2);
try {
InputStreamReader read = new InputStreamReader(file.getInputStream(), "utf-8");
BufferedReader bufferedReader = new BufferedReader(read);
StringBuffer jsonContent = new StringBuffer();
String content = "";
while ((content = bufferedReader.readLine()) != null) {
jsonContent.append(content);
}
String filePath = "D://filetest.txt";
File date = new File(filePath);
FileOutputStream fop = null;
fop = new FileOutputStream(date);
byte[] contentInBytes = jsonContent.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
read.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}