//pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
param就是完整的json请求字符串
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
private boolean save2file(String url, String param, String fileName){
HttpPost post = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
post.setEntity(new StringEntity(param, ContentType.APPLICATION_JSON));
try {
CloseableHttpResponse response = httpClient.execute(post);
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
}
FileOutputStream fos = new FileOutputStream(fileName);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
return false;
}
log.info("file:{}",new File(fileName).getAbsolutePath());
return true;
}