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 "";
    }
  • 相关阅读:
    Sliverlight之 矢量绘图
    Silverlight之 xaml布局
    七天学会ASP.NET MVC(七)——创建单页应用
    MVC视图之间调用方法总结
    C#取得程序的根目录以及判断文件是否存在
    七天学会ASP.NET MVC (六)——线程问题、异常处理、自定义URL
    [C#] .NET4.0中使用4.5中的 async/await 功能实现异步
    C#中StreamReader读取中文文本出现乱码的解决方法
    七天学会ASP.NET MVC (五)——Layout页面使用和用户角色管理
    常用正则表达式
  • 原文地址:https://www.cnblogs.com/yizw/p/14456165.html
Copyright © 2011-2022 走看看