//构建图床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; }
HttpClient构建请求,并发送请求
最新推荐文章于 2024-08-09 11:39:46 发布