java后台模拟post请求上传图片

 public static JsonRtn<?> uploadImage(String filePath, String uploadUrl,String cookie) {
       
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        String jsonStr = "";
        try {
            URL url1 = new URL(uploadUrl);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            String boundary = "----WebKitFormBoundary" + createRandCode().substring(0, 16);
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("Cookie", cookie);
            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\n", file.getName()).getBytes());
            output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len = 0;
            FileInputStream input = new FileInputStream(file);
            while ((len = input.read(data)) > -1) {
                output.write(data, 0, len);
            }
            output.write(("\r\n--" + boundary + "--").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while ((len = resp.read(data)) > -1)
                sb.append(new String(data, 0, len, "utf-8"));
            resp.close();
            jsonStr = sb.toString();
            System.out.println(jsonStr);
          
        } catch (ClientProtocolException e) {
            logger.info(CLASS_NAME + "postFile,不支持http协议" + e.toString());
           
        } catch (IOException e) {
            logger.info("postFile数据传输失败" + e);
           
        }
    }



 /**
     * 获取一个随机字符串
     *
     * @return
     */
    private static String createRandCode() {
        char[] chars = new char[35];
        short start = '0';
        //如果此处没有加法,那么一个随机数取到1才会获得字符‘z’。所以此处+1即可,理论封顶是加到14,超过14就会取得其余字符,但我们通过了方法判断字符,不用担心!
        short end = 'z' + 14;
        for (int i = 0; i < chars.length; i++) {
            while (true) {
                char orderNum = (char) (Math.random() * (end - start) + start);
                if (Character.isLetter(orderNum) || Character.isDigit(orderNum)) {
                    chars[i] = orderNum;
                    /*System.out.println("orderNum:" + orderNum);*/
                    break;
                }
            }
        }
        String str = new String(chars);
        return str;
    }

直接上代码,亲测有效!!!需要注意的地方是图片后台接收的名称需要修改,我这里后台接收的名称是file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值