用到的jar包有
- httpclient-4.5.10.jar
- httpmime-4.5.13.jar
- httpcore-4.4.12.jar
public static byte[] sendPost(String url, byte[] fileBytes)
{
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建post方法连接实例,在post方法中传入待连接地址
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try
{
//设置请求参数
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
//设置浏览器兼容模式,出现乱码可以设置成HttpMultipartMode.RFC6532
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//设置编码
entity.setCharset(Charset.forName(CommonConstants.CODE_UTF8));
if (fileBytes != null)
{
//内容类型,用于定义网络文件的类型和网页的编码,决定文件接收方将以什么形式、什么编码读取这个文件
ContentType contentType = ContentType.create("application/octet-stream",
Charset.forName(CommonConstants.CODE_UTF8));
//添加二进制文件,"image"类似于Map的key,接受方通过该字段获取数据。
entity.addBinaryBody("image", fileBytes, contentType, fileName);
}
httpPost.setEntity(entity.build());
//发起请求,并返回请求响应
response = httpClient.execute(httpPost);
//接受请求返回的文件或json
HttpEntity result = response.getEntity();
InputStream instream = result.getContent();
return IOUtils.toByteArray(instream);
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
response.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
————————————
作者:学习要趁早z
链接:https://blog.csdn.net/qq_42677452/article/details/121162631
版权声明:本文为CSDN博主「学习要趁早z」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。