1. 程式人生 > >java之微信開發回覆圖片訊息

java之微信開發回覆圖片訊息

微信開發文件見:詳見
具體實現見:詳見

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"); } }