微信-上传图文消息内的图片获取URL-java-post图片

微信公众号图片上传接口解析

上传图文消息内的图片获取URL
本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。

接口调用请求说明

http请求方式: POST,https协议
https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
调用示例(使用curl命令,用FORM表单方式上传一个图片):
curl -F media=@test.jpg “https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
参数说明

参数 是否必须 说明
access_token 是 调用接口凭证
media 是 form-data中媒体文件标识,有filename、filelength、content-type等信息
返回说明 正常情况下的返回结果为:

{

“url”: “http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYs CNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0”

}
其中url就是上传图片的URL,可放置图文消息中使用。

/**
     * 上传图文消息内的图片获取URL
     * @param file
     * @param access
     * @return
     */
    private String getUpWxImgUrl(File file,String access) {
        String url = WX_IMG_UP_URL + access;
        String jsonStr = FormUpdate.formUpload(url, file);
        String returnUrl = "";
        if(jsonStr.indexOf("errcode") == -1) {
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            returnUrl = jsonObject.get("url").toString();
        }
        return returnUrl;
    }
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.activation.MimetypesFileTypeMap;

public class FormUpdate {
    /**
     * 上传图片 
     * 
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @return
     */
    public static String formUpload(String urlStr, File file) {
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // file
            String inputName = "";
            String filename = file.getName();
            String contentType = new MimetypesFileTypeMap().getContentType(file);
            if (filename.endsWith(".png")) {
                contentType = "image/png";
            }
            if (contentType == null || contentType.equals("")) {
                contentType = "application/octet-stream";
            }

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append(
                    "Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            // 读取返回数据
            StringBuffer strBuf2 = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf2.append(line).append("\n");
            }
            res = strBuf2.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }

}
### 推送图文消息到企业微信的实现方法 企业微信支持通过其API推送图文消息,开发者可以通过构造特定的JSON请求体来实现这一功能。以下是一个完整的实现方法,包括关键参数说明和示例代码。 #### 关键参数说明 - **touser**:指定接收消息的用户ID列表,多个用户ID之间用 `|` 分隔。 - **toparty**:指定接收消息的部门ID列表,多个部门ID之间用 `|` 分隔。 - **totag**:指定接收消息的标签ID列表,多个标签ID之间用 `|` 分隔。 - **msgtype**:消息类型,此处为 `news`,表示图文消息- **agentid**:应用的唯一标识,需替换为企业微信应用中的实际ID。 - **news**:图文消息的具体内容,包含多个图文项(articles),每个图文项包括标题、描述、图片URL和跳转链接。 #### 示例代码(Java实现) 以下是一个使用Java发送图文消息的示例代码: ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import com.alibaba.fastjson.JSONObject; public class WeComNewsMessageSender { private static final String ACCESS_TOKEN = "your_access_token"; // 替换为实际的access_token private static final String SEND_MESSAGE_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + ACCESS_TOKEN; public static void sendNewsMessage() { try { // 构建请求体 JSONObject message = new JSONObject(); message.put("touser", "UserID1|UserID2"); message.put("toparty", "PartyID1"); message.put("totag", "TagID1"); message.put("msgtype", "news"); message.put("agentid", 100001); // 替换为企业微信应用的实际ID // 构建图文消息内容 JSONObject news = new JSONObject(); JSONArray articles = new JSONArray(); JSONObject article1 = new JSONObject(); article1.put("title", "中秋节礼品领取"); article1.put("description", "今年中秋节公司有豪礼相送"); article1.put("url", "https://example.com"); article1.put("picurl", "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png"); articles.add(article1); news.put("articles", articles); message.put("news", news); // 发送POST请求 URL url = new URL(SEND_MESSAGE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); OutputStream output = connection.getOutputStream(); output.write(message.toJSONString().getBytes("UTF-8")); output.close(); // 获取响应 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { sendNewsMessage(); } } ``` #### 注意事项 - 需要先获取 `access_token`,该令牌是调用企业微信API的必要参数,可以通过企业ID和应用密钥获取- 确保 `agentid` 和接收消息的用户、部门、标签等参数正确无误。 - 图文消息中的 `url` 字段应为有效的链接地址,确保用户点击后能够正常跳转[^3]。 --- ###
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦里藍天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值