zoukankan      html  css  js  c++  java
  • HttpURLConnection发送post请求推送图片

    /**
     * 推送文件
     * @param uploadUrl 推送url
     * @param bbyte 文件字节数组
     * @param fileName 文件名
     * @param parmas post请求的其他参数
     * @return
     */
    public static String uploadFile(String uploadUrl, byte[] bbyte,String fileName,Map<String,Object> parmas) {
       String end = "
    ";
       String twoHyphens = "--";
       String boundary = "MyBoundary" + System.currentTimeMillis();
       try {
          URL url = new URL(uploadUrl);
          HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
          httpURLConnection.setDoInput(true);
          httpURLConnection.setDoOutput(true);
          httpURLConnection.setUseCaches(false);
          httpURLConnection.setRequestMethod("POST");
          httpURLConnection.setRequestProperty("Connection", "Keep-alive");
          httpURLConnection.setRequestProperty("Charset", "UTF-8");
          httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    
          DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
          for (Map.Entry<String,Object> entry : parmas.entrySet()){
             String key = entry.getKey();
             String value = (String) entry.getValue();
             dos.writeBytes(twoHyphens + boundary + end);
             dos.writeBytes("Content-Disposition: form-data; name=""+key+""" + end + end);
             dos.writeBytes(value);
             dos.writeBytes(end);
          }
          dos.writeBytes(twoHyphens + boundary + end);
          dos.writeBytes("Content-Disposition: form-data; name="image"; filename=""+fileName+""" + end);
          String contentType = "Content-Type: application/octet-stream" + end + end;
          dos.write(contentType.getBytes());
          dos.write(bbyte);
          dos.writeBytes(end);
          String endStr = twoHyphens + boundary + twoHyphens + end;
          dos.write(endStr.getBytes());
          // 读取服务器返回结果
          InputStream is = httpURLConnection.getInputStream();
          InputStreamReader isr = new InputStreamReader(is, "utf-8");
          BufferedReader br = new BufferedReader(isr);
          String result = br.readLine();
          is.close();
          return  result;
       } catch (Exception e) {
          e.printStackTrace();
       }
       return "";
    }
  • 相关阅读:
    ELF 格式简介
    gdb 使用说明;ARM 汇编
    博士研究生的组会PPT汇报相关-labgirls
    浅尝辄止·认识Blazor及基础使用
    VBA·Function的基础使用
    WCF·无法自动进入并单步执行服务器。调试器未能在服务器进程中停止。
    Word·查找任意汉字的方法
    VBA·编译错误:ByRef参数类型不符
    排坑·QQ浏览器打开MD文件时显示下载不能直接打开
    MSSQL·PIVOT关键字实现列转行
  • 原文地址:https://www.cnblogs.com/yizw/p/14456165.html
Copyright © 2011-2022 走看看