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 "";
    }
  • 相关阅读:
    js 正则验证输入框只允许输入正实数和正整数和负整数
    阿里maven镜像服务器配置
    JDK环境变量配置
    AndroidStudio OpenCv的配置,不用安装opencv manager
    Java实现红黑树
    基于红黑树的骨架提取Java
    基于Mat变换的骨架提取Java
    Java实现二叉树的四种遍历
    Java实现常见的几种排序
    hough变换检测直线Java
  • 原文地址:https://www.cnblogs.com/yizw/p/14456165.html
Copyright © 2011-2022 走看看