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 = "\r\n";
   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 "";
}

 

posted @ 2021-02-27 16:23  yizw  阅读(411)  评论(0编辑  收藏  举报