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 "";
    }
  • 相关阅读:
    Bootstrap模态框modal的高度和宽度设置
    入门学习Linux常用必会命令实例详解
    Linux 系统中用户切换(su user与 su
    hdu 3549 Flow Problem(最大流模板题)
    第三章 学后心得及总结 【物联网1132-11】
    Find Minimum in Rotated Sorted Array 旋转数组中找最小值 @LeetCode
    面试题4
    Fp关联规则算法计算置信度及MapReduce实现思路
    POJ 1679 The Unique MST 推断最小生成树是否唯一
    论程序猿的社会地位
  • 原文地址:https://www.cnblogs.com/yizw/p/14456165.html
Copyright © 2011-2022 走看看