爱玺玺

爱玺玺的生活日记本。wx:lb87626

java模拟post payload模拟上传图片,如果只传图片,一定要把处理文本的删除了,不然会报空错误。

主要实现美团大众客后台客服传图片功能

注意String BOUNDARY = "------WebKitFormBoundaryk39DRPjsO0rkeABP";所有地方都一样


package tools;

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 java.util.HashMap;

import java.util.Iterator;

import java.util.Map;


import javax.activation.MimetypesFileTypeMap;


import org.json.JSONException;

import org.json.JSONObject;



import tools.MyUtils;


/**

 * java通过模拟post方式提交表单实现图片上传功能实例

 * 其他文件类型可以传入 contentType 实现

 */

public class PostFile2 {

public String PostPic(String picPath,String token,String expireTime) {

Object object = null;

String myUploadImage = this.MyUploadImage(picPath,token,expireTime);

/*

try {

JSONObject jsonObject = new JSONObject(myUploadImage);

JSONObject jsonObject2 = new JSONObject(jsonObject.get("respD")+"");

object = jsonObject2.get("url");

return object+"";

} catch (JSONException e) {

e.printStackTrace();

}

*/

return object+"";

}


    private String MyUploadImage(String picPath,String token,String expireTime){

        String url = "https://pic.meituan.com/extrastorage/mim";

        String reader = picPath;

        File file=new File(picPath);

        /*模拟文本域*/

        Map<String, String> textMap = new HashMap<String, String>();

        //可以设置多个input的name,value

        textMap.put("name",file.getName());


        

        //设置file的name,路径,模拟上传文件

        Map<String, String> fileMap = new HashMap<String, String>();

        System.out.println("文件路径:"+reader);

        fileMap.put("file", reader);

        String contentType = "";//image/png

        

        String ret = formUpload(url, textMap, fileMap,contentType,token,expireTime);

        return ret;

    }


    /**

     * 上传图片

     * @param urlStr

     * @param textMap

     * @param fileMap

     * @param contentType 没有传入文件类型默认采用application/octet-stream

     * contentType非空采用filename匹配默认的图片类型

     * @return 返回response数据

     */

    @SuppressWarnings("rawtypes")

    private static String formUpload(String urlStr, Map<String, String> textMap,

                                    Map<String, String> fileMap,String contentType,String token,String expireTime) {

        String res = "";

        HttpURLConnection conn = null;

        // boundary就是request头和上传文件内容的分隔符

        String BOUNDARY = "------WebKitFormBoundaryk39DRPjsO0rkeABP";

        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("Accept", "application/json, text/javascript");

            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");

            conn.setRequestProperty("Authorization", token);

            conn.setRequestProperty("Connection", "keep-alive");

            conn.setRequestProperty("Content-Length", "1387582");

            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            conn.setRequestProperty("Host", "pic.meituan.com");

            conn.setRequestProperty("Origin", "https://g.dianping.com");

            conn.setRequestProperty("Referer", "https://g.dianping.com/");

            conn.setRequestProperty("sec-ch-ua", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"");

            conn.setRequestProperty("sec-ch-ua-mobile", "?0");

            conn.setRequestProperty("sec-ch-ua-platform", "\"Windows\"");

            conn.setRequestProperty("Sec-Fetch-Dest", "empty");

            conn.setRequestProperty("Sec-Fetch-Mode", "cors");

            conn.setRequestProperty("Sec-Fetch-Site", "cross-site");

            conn.setRequestProperty("time",expireTime);

            //conn.setRequestProperty("time", "1663591697038");

            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36");

            

            System.out.println(token);

            System.out.println(expireTime);

            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // text

            /*注释掉处理文本部分

            if (textMap != null) {

                StringBuffer strBuf = new StringBuffer();

                Iterator iter = textMap.entrySet().iterator();

                while (iter.hasNext()) {

                    Map.Entry entry = (Map.Entry) iter.next();

                    String inputName = (String) entry.getKey();

                    String inputValue = (String) entry.getValue();

                    if (inputValue == null) {

                        continue;

                    }

                    strBuf.append("\r\n").append("--").append(BOUNDARY)

                            .append("\r\n");

                    strBuf.append("Content-Disposition:form-data;name=\""

                            + inputName + "\"\r\n\r\n");

                    strBuf.append(inputValue);

                }

                out.write(strBuf.toString().getBytes());

            }

            */

            // file

            if (fileMap != null) {

                Iterator iter = fileMap.entrySet().iterator();

                while (iter.hasNext()) {

                    Map.Entry entry = (Map.Entry) iter.next();

                    String inputName = (String) entry.getKey();

                    String inputValue = (String) entry.getValue();

                    System.out.println("图片路径:"+inputValue);

                    if (inputValue == null) {

                        continue;

                    }

                    File file = new File(inputValue);

                    String filename = file.getName();


                    //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream

                    contentType = new MimetypesFileTypeMap().getContentType(file);

                    //contentType非空采用filename匹配默认的图片类型

                    if(!"".equals(contentType)){

                        if (filename.endsWith(".png")) {

                            contentType = "image/png";

                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {

                            contentType = "image/jpeg";

                        }else if (filename.endsWith(".gif")) {

                            contentType = "image/gif";

                        }else if (filename.endsWith(".ico")) {

                            contentType = "image/image/x-icon";

                        }

                    }

                    if (contentType == null || "".equals(contentType)) {

                        contentType = "application/octet-stream";

                    }

                    StringBuffer strBuf = new StringBuffer();

                    strBuf.append("\r\n").append("--").append(BOUNDARY)

                            .append("\r\n");

                    System.out.println("Content-Disposition:form-data;name=\""

                            + inputName + "\";filename=\"" + filename

                            + "\"\r\n");

                    strBuf.append("Content-Disposition:form-data;name=\""

                            + inputName + "\";filename=\"" + filename

                            + "\"\r\n");

                    System.out.println(contentType);

                    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 strBuf = new StringBuffer();

            BufferedReader reader = new BufferedReader(new InputStreamReader(

                    conn.getInputStream()));

            String line = null;

            while ((line = reader.readLine()) != null) {

                strBuf.append(line).append("\n");

            }

            res = strBuf.toString();

            reader.close();

            reader = null;

        } catch (Exception e) {

            System.out.println("发送POST请求出错。" + urlStr);

            e.printStackTrace();

        } finally {

            if (conn != null) {

                conn.disconnect();

                conn = null;

            }

        }

        System.out.println(res);

        return res;

    }


}



调用这个类的方法:

package danduyong;


import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;


import com.alibaba.fastjson.JSON;


import tokenbean.Msg;

import tokenbean.TokenJson;

import tools.MyUtils;

import tools.PostFile2;


/**

 * 1.获取大众对话框所有顾客,具体有多少不知道,需要测试,后面可以再写给订单的,不过下订单的一般都应咨询过

 * 2.查出发生消息需要的参数,直接测试,不用以前的潜客看行不行,潜客用的应该不是同一个接口,因为潜客会判断是否已发,而聊天窗口不用,所以重新写一个。

 * 3.又发现30天以外的不能发,只能发30天以内的,只有测试下了。

 * @author ASUS

 *

 */

public class SendMsg {


private static MyUtils myUtils;


public static void main(String[] args) {

myUtils = new MyUtils();

//读取对话框所有顾客

//String readHttp = myUtils.readHttp("https://m.dianping.com/dzim/message/shopchatgrouplist?offset=700&limit=50&chatgrouptype=2&shopid=&clienttype=100900");

String tokenjson = myUtils.readHttp("https://m.dianping.com/dzim/message/merchant/image/gettoken?type=token&clienttype=100900&shopid=s129383121");

System.out.println(tokenjson);

TokenJson parseObject = JSON.parseObject(tokenjson, TokenJson.class);

Msg msg = parseObject.getMsg();

//模拟第一个min请求

String result = "";

URL url;

HttpURLConnection conn = null;

InputStream in=null;

try {

url = new URL("https://pic.meituan.com/extrastorage/mim");

conn = (HttpURLConnection) url.openConnection();

conn.setRequestProperty("Accept", "*/*");

conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");

conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");

conn.setRequestProperty("Access-Control-Request-Headers", "authorization,time");

conn.setRequestProperty("Access-Control-Request-Method", "POST");

conn.setRequestProperty("Connection", "keep-alive");

conn.setRequestProperty("Host", "pic.meituan.com");

conn.setRequestProperty("Origin", "https://g.dianping.com");

conn.setRequestProperty("Referer", "https://g.dianping.com/");

conn.setRequestProperty("Sec-Fetch-Dest", "empty");

conn.setRequestProperty("Sec-Fetch-Mode", "cors");

conn.setRequestProperty("Sec-Fetch-Site", "cross-site");

conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36");


in=conn.getInputStream();

int len = 0;

byte[] buffer = new byte[1024];

while ((len = in.read(buffer)) > 0) {

result += new String(buffer, 0, len);

}

in.close();

conn.disconnect();

} catch (Exception e1) {

conn.disconnect();

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

e1.printStackTrace();

}

//String picpath="uploadImg/1663594773649.jpg";

//String picpath="D://dz.jpg";

String picpath="D:/dz.jpg";

//String picpath="D:dz.jpg";

//String picpath="D:\\dz.jpg";

PostFile2 postFile2 = new PostFile2();

String picUrl = postFile2.PostPic(picpath,msg.getToken(),msg.getExpireTime()+"");

}


}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5