java使用httpclient下载需要post参数json的文件

//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;
    }
发布了259 篇原创文章 · 获赞 118 · 访问量 187万+

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/104284559