参考文档 微信B2B申请微信支付商户号
package com.test.main;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @author
* @version 1.0
* @description: 上传微信B2B商户图片资料
* @date 2024/9/19 11:25
*/
public class 上传微信B2B商户图片资料 {
public static String URL = "https://api.weixin.qq.com/retail/B2b/retailuploadmchfile?access_token=";
public static void main(String[] args) {
// 微信小程序accesstoken
String accessToken = "";
String requestUrl = URL + accessToken;
// 图片地址, 如果是本地图片调整代码
String url = "https://obs.cn-north-4.myhuaweicloud.com/6a68983691e34107af4bb85564013a1b.jpeg";
// 创建一个HttpPost请求
Map<String, Object> paramMap = new HashMap<>();
String fileName = FileUtils.getName(url);
String tmpPath = "/tmp/" + fileName;
// 设置文件名
paramMap.put("file_name", fileName);
// 设置文件数据
File file = FileUtil.writeBytes(HttpRequest.get(url).execute().bodyBytes(), tmpPath);
// 这里将图片转成base64
paramMap.put("file", FileUtils.fileToBase64(file.getAbsoluteFile()));
try {
String result = HttpUtil.post(requestUrl, JSON.toJSONString(paramMap));
// {"errcode":0,"errmsg":"OK","file_id":"V1_jm59ObDkLJOzY9eQhmv6giwKWUAjk"}
System.out.println(result);
} finally {
file.delete();
}
}
public static class FileUtils {
/** 字符常量:斜杠 {@code '/'} */
public static final char SLASH = '/';
/** 字符常量:反斜杠 {@code '\\'} */
public static final char BACKSLASH = '\\';
/**
* 返回文件名
*
* @param filePath 文件
* @return 文件名
*/
public static String getName(String filePath)
{
if (null == filePath)
{
return null;
}
int len = filePath.length();
if (0 == len)
{
return filePath;
}
if (isFileSeparator(filePath.charAt(len - 1)))
{
// 以分隔符结尾的去掉结尾分隔符
len--;
}
int begin = 0;
char c;
for (int i = len - 1; i > -1; i--)
{
c = filePath.charAt(i);
if (isFileSeparator(c))
{
// 查找最后一个路径分隔符(/或者\)
begin = i + 1;
break;
}
}
return filePath.substring(begin, len);
}
/**
* 是否为Windows或者Linux(Unix)文件分隔符<br>
* Windows平台下分隔符为\,Linux(Unix)为/
*
* @param c 字符
* @return 是否为Windows或者Linux(Unix)文件分隔符
*/
public static boolean isFileSeparator(char c)
{
return SLASH == c || BACKSLASH == c;
}
/**
*
* @param file 文件
* @return String
* @description 将文件转base64字符串
* @date 2019年11月24日
* @author rmk
*/
public static String fileToBase64(File file) {
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
in.read(bytes);
base64 = new String(Base64.encodeBase64(bytes),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
}
}

被折叠的 条评论
为什么被折叠?



