爱玺玺

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

java模拟浏览器上传post文本域和文件图片

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 tools.MyUtils;


/**

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

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

 */

public class Test {


    public static void main(String[] args) {

        testUploadImage();


    }


    /**

     * 测试上传png图片

     *

     */

    public static void testUploadImage(){

        String url = "https://b.soyoung.com/saas/sendMessage";

        String lunboimg = "D:/2.jpg";

        String reader = "D:/2.jpg";

        /*模拟文本域*/

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

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

        textMap.put("type", "2");

        textMap.put("fid", "32967372");

        textMap.put("fid", "32967372");

        textMap.put("host_uid", "12730430");

        textMap.put("saas_token", "8d98e56f41fbf1504f30dea8a11e3e75");

        textMap.put("saas_timestamp", "1572943513");

        textMap.put("saas_sign", "f3e5f68f6732aad4e788bc3ce7059c43");


        

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

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

        fileMap.put("lunboimg", lunboimg);

        fileMap.put("file", reader);

        String contentType = "";//image/png

        

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

        System.out.println(ret);

        //{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"}

    }


    /**

     * 上传图片

     * @param urlStr

     * @param textMap

     * @param fileMap

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

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

     * @return 返回response数据

     */

    @SuppressWarnings("rawtypes")

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

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


        String res = "";

        HttpURLConnection conn = null;

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

        String BOUNDARY = "---------------------------123821742118716";

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

            conn.setRequestProperty(

    "Cookie","__usersign__=1572918625442771203; _ga=GA1.2.1124308716.1572918626; _gid=GA1.2.1260008433.1572918626; Hm_lvt_b366fbb5465f5a86e1cc2871552e1fdb=1572578753,1572743314,1572829596,1572918626; smidV2=2019101610044448988524c7edeaeb3089435bc17f62d7007303b25d3f52900; PHPSESSID=d21a2f39badef5e349c4437438d0a592; aef2c5a50ef97224a9d78c44f0c7cf9f=b5192ebe6b82bc8e014615509eacaa694f303838a%3A4%3A%7Bi%3A0%3Bs%3A8%3A%2212730430%22%3Bi%3A1%3Bs%3A51%3A%223_oso0Jt9Q5bPMzMhm0NZfFgZfhy9s1493019438%40weixin.com%22%3Bi%3A2%3Bi%3A86400%3Bi%3A3%3Ba%3A13%3A%7Bs%3A9%3A%22user_name%22%3Bs%3A33%3A%22%E6%88%90%E9%83%BD%E7%BE%8E%E7%BB%BD%E7%BE%8E%E6%95%B4%E5%BD%A2%E7%BE%8E%E5%AE%B9%E5%8C%BB%E9%99%A2%22%3Bs%3A6%3A%22gender%22%3Bs%3A1%3A%220%22%3Bs%3A6%3A%22avatar%22%3Bs%3A77%3A%22https%3A%2F%2Fimg2.soyoung.com%2Fuser%2F20190312%2F0%2F632fa8739987c4307e170dd73535dd2b.png%22%3Bs%3A9%3A%22user_type%22%3Bs%3A3%3A%22102%22%3Bs%3A11%3A%22admin_level%22%3Bs%3A1%3A%220%22%3Bs%3A6%3A%22ban_yn%22%3Bs%3A1%3A%220%22%3Bs%3A6%3A%22gag_yn%22%3Bs%3A1%3A%220%22%3Bs%3A14%3A%22gag_start_time%22%3Bs%3A1%3A%220%22%3Bs%3A12%3A%22gag_end_time%22%3Bs%3A1%3A%220%22%3Bs%3A14%3A%22certified_type%22%3Bs%3A1%3A%222%22%3Bs%3A12%3A%22certified_id%22%3Bs%3A6%3A%22107244%22%3Bs%3A12%3A%22login_mobile%22%3Bs%3A0%3A%22%22%3Bs%3A10%3A%22admin_team%22%3Ba%3A0%3A%7B%7D%7D%7D; login_uid=12730430; login_token=6e4ba3d5ab5147355bf9e79e3bc47f91; __guid=31545325.3004972117047928000.1572918654296.8704; __order_time__=2019-11-05 09:50:55; msg_time=1572918661; back_order_time=2019-11-05 09:51:07; complain_time=2019-11-05 09:51:13; free_surgery_time=2019-11-05 10:00:04; activity_notice_time=2019-11-05 10:00:06; Hm_lpvt_b366fbb5465f5a86e1cc2871552e1fdb=1572944065; __newmsg__=%7B%22code%22%3A200%2C%22cnt%22%3A%220%22%2C%22cache%22%3A0%2C%22msg_cnt%22%3A0%2C%22msg_cnt_nread%22%3A0%2C%22total%22%3A0%2C%22order_cnt%22%3A1%2C%22order_msg%22%3A%22261524022%22%2C%22order_time%22%3A1572927509%2C%22back_order%22%3A0%2C%22back_order_msg%22%3A%22%22%2C%22hospital_yn%22%3A1%2C%22time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22back_order_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22private_back_order_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22msg_time%22%3A1572944123%2C%22private_msg_time%22%3A1572943317%2C%22doctor_yn%22%3A0%2C%22complain%22%3A%22%22%2C%22complain_msg%22%3A%22%22%2C%22complain_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22private_complain_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22freeSurgery%22%3A%5B%5Bnull%2C1%5D%2C%5Bnull%2C2%5D%2C%5Bnull%2C3%5D%2C%5Bnull%2C4%5D%2C%5Bnull%2C5%5D%5D%2C%22freeSurgery_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22private_freeSurgery_time%22%3A%5B%5Bnull%2C1%5D%2C%5Bnull%2C2%5D%2C%5Bnull%2C3%5D%2C%5Bnull%2C4%5D%2C%5Bnull%2C5%5D%5D%2C%22activity_notice_status%22%3A%5B%5B0%2C0%2C%22%22%2C0%2C1%5D%2C%5B0%2C0%2C%22%22%2C0%2C2%5D%2C%5B0%2C0%2C%22%22%2C0%2C3%5D%5D%2C%22activity_notice_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22private_activity_notice_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22activity_pass_time%22%3A%222019-11-05+16%3A55%3A23%22%2C%22activity_no_pass_time%22%3A%222019-11-05+16%3A55%3A23%22%7D; monitor_count=60");

    conn.setRequestProperty("Origin", "https://b.soyoung.com");

    conn.setRequestProperty("referer",

    "https://b.soyoung.com/saas/msg?fid=32967372&host_uid=12730430");

            

            

            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();

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

                    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 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;

            }

        }

        return res;

    }


}



发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5