微信开发文档见:详见
具体实现见:详见
public class WxController {
public static final Logger LOGGER= LoggerFactory.getLogger(WxController.class);
//type传image
public static String upload(String accessToken,String filePath,String type) throws IOException {
//判断文件是否存在
File file=new File(filePath);
if (!file.exists() || !file.isFile()){
throw new IOException("文件不存在");
}
//新建请求url
String url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type="+type;
URL u=new URL(url);
HttpURLConnection connection= (HttpURLConnection) u.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
//设置头信息
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("Charset","UTF-8");
//设置边界
String bound="-------"+ System.currentTimeMillis();
connection.setRequestProperty("Content-Type","multipart/form-data; boundary="+bound);
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("--").append(bound).append("\r\n").
append("Content-Disposition:form-data;name=\"file\";filename=\""+file.getName()+"\"\r\n").
append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head=stringBuilder.toString().getBytes("utf-8");
//获得输出流
OutputStream outputStream=new DataOutputStream(connection.getOutputStream());
outputStream.write(head);
//文件正文
DataInputStream in=new DataInputStream(new FileInputStream(file));
int bytes=0;
byte[] buffer=new byte[1024];
while((bytes=in.read(buffer))!=-1){
outputStream.write(buffer,0,bytes);
}
in.close();
//文件结尾
byte[] foot=("\r\n--"+bound+"--\r\n").getBytes("utf-8");
outputStream.write(foot);
outputStream.flush();
outputStream.close();
StringBuffer stringBuffer=new StringBuffer();
BufferedReader bufferedReader=null;
String result=null;
try {
//获取url响应
bufferedReader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line=null;
while ((line=bufferedReader.readLine())!=null){
stringBuffer.append(line);
}
if (result==null){
result=stringBuffer.toString();
}
}catch (IOException e){
e.printStackTrace();
}finally {
if (bufferedReader!=null){
bufferedReader.close();
}
}
//转化结果
JSONObject jsonObject= JSON.parseObject(result);
LOGGER.info(jsonObject.toJSONString());
String typeName="media_id";
if (!"image".equals(type)){
typeName=type+"_media_id";
}
String media_id= (String) jsonObject.get(typeName);
LOGGER.info(media_id);
return media_id;
}
public static void main(String[] args) throws IOException {
//获取accesstoken
//调用上传方法获得media_id
String path="D:\\pang.png";
String media_id=upload("access",path,"image");
}
}