WeChat-Upload the picture in the picture and text message to get the URL-java-post picture

Upload the picture in the image and text message to obtain the URL
The pictures uploaded by this interface do not occupy the limit of 5000 pictures in the material library of the official account. The image only supports jpg/png format, and the size must be less than 1MB.

Interface call request description

http request method: POST, https protocol
https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
Call example (using the curl command to upload a picture in the FORM form):
curl -F [email protected] " https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN "
parameter description

Whether the parameter must indicate that
access_token is the calling interface certificate
media is the media file identifier in form-data, with information such as filename, filelength, content-type, etc.
Return explanation The return result under normal circumstances is:

{

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

}
Where url is the URL of the uploaded image, which can be placed in the text message.

/**
     * 上传图文消息内的图片获取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;
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324522609&siteId=291194637