public static String httpPostWithJSON(String url, String json) throws Exception {
String result = null;
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
//参数
StringEntity se = new StringEntity(json,"utf-8");
se.setContentType("application/json");
se.setContentEncoding("UTF-8");
//设置请求参数
httpPost.setEntity(se);
//发送请求
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
InputStream instreams = resEntity.getContent();
result = getBase64FromInputStream(instreams);
result = "data:image/png;base64,"+result;
}
httpPost.abort();
return result;
}
/*
* @param instreams 二进制流
*
* @param imgPath 图片的保存路径
*
* @param imgName 图片的名称
*
* @return 1:保存正常 0:保存失败
*/
public static String saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) {
String path = "";
int stateInt = 1;
if (instreams != null) {
try {
File file = new File(imgPath + imgName);// 可以是任何图片格式.jpg,.png等
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int nRead = 0;
while ((nRead = instreams.read(b)) != -1) {
fos.write(b, 0, nRead);
}
fos.flush();
fos.close();
} catch (Exception e) {
stateInt = 0;
e.printStackTrace();
} finally {
try {
instreams.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return path;
}
/**
*
* 转base64
*
* */
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new String(Base64.encodeBase64(data));
}
java spring boot 小程序二维码 base64
猜你喜欢
转载自blog.csdn.net/a961011576/article/details/85098760
今日推荐
周排行