微信公众平台官方文档
我在本地使用工具请求接口一切正常。
当我开始写代码的时候 我蒙了 后台怎么模拟form表单上传图片
放参考文章链接https://blog.csdn.net/subaiqiao/article/details/122059076
首先引入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.4.1</version>
</dependency>
上传代码
/**
* 微信服务器新增临时素材
* 封面图片
* @param file
* 图片file
* @param token
* access_token
*/
public static JSONObject uploadTemporaryMedia(File file, String token) throws IOException {
if (file == null || token == null) {
return null;
}
if (!file.exists()) {
return null;
}
String responseData = null;
try {
String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+token+"&type=image";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("image/png");
RequestBody fileBody = RequestBody.create(mediaType, file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("media", file.getName(), fileBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
responseData = response.body().string();
System.out.println(responseData);
}catch (Exception e){
e.printStackTrace();
}
// return result;
return JSONObject.parseObject(responseData);
}