HttpClient构建请求,并发送请求

//构建图床HttpPost,用于发送请求
public HttpPost createHttpPostForPath(String path,MultipartFile file,String filename) throws IOException {
    HttpPost httpPost = new HttpPost(url);
    ContentType type=ContentType.MULTIPART_FORM_DATA.withCharset("UTF-8");
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file",file.getBytes(),type,filename)
            .addTextBody("bucket",bucket)
            .addTextBody("secret_key",secret_key)
            .addTextBody("path",path)
            .setCharset(Charset.forName("UTF-8"))
            .setContentType(type)
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .build();
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout)
            .build();
    httpPost.setConfig(requestConfig);
    httpPost.setEntity(reqEntity);

    return httpPost;
}

//发送请求,将图图片保存在图速运
/**
 *@param imagePath 图片在云速图的存储目录
 * @param file 前端的上传的图片文件
 * @param fileName 作为云速图的图片名字
 * @return message code==200为上传成功 message为云速图的访问路径
 */
public Message saveImage(String imagePath,MultipartFile file, String fileName) throws IOException {
    Message message = new Message();
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    CloseableHttpResponse closeableHttpResponse = null;
    HttpPost httpPost = this.createHttpPostForPath(imagePath, file, fileName);
    try {
        closeableHttpResponse = httpclient.execute(httpPost);  //发起请求
        System.out.println("----------------------------------------");

        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            HttpEntity resEntity = closeableHttpResponse.getEntity();
            String jsonString = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                YuSuTuSuccessRes res = objectMapper.readValue(jsonString, YuSuTuSuccessRes.class);
                System.out.println(res);
                if (res.getCode() == 0) {  //图片上传成功
                    message.setCode(MessageUtil.SUCCESS_CODE);
                    message.setMessage(res.getData().getPath());
                    return message;
                }
            }
            EntityUtils.consume(resEntity);
        }
    } finally {
        try {
            // 释放资源
            if (httpclient != null) {
                httpclient.close();
            }
            if (closeableHttpResponse != null) {
                closeableHttpResponse.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return message;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值