Java http请求(二) ---- 文件上传工具

http请求(二) ---- 文件上传工具

 public class FormFile {
      // 上传文件的数据
      private byte[] data;
 
     private InputStream inStream;

    // 文件名称
    private String filename;
     // 表单名称
     private String formname;
     // 内容类型
    private String contentType = "application/octet-stream";
 
    public FormFile(String filename, byte[] data, String formname,
             String contentType) {
         this.data = data;
        this.filename = filename;
         this.formname = formname;
         if (contentType != null) {
             this.contentType = contentType;
         }
     }
 
   public FormFile(String filename, InputStream inStream, String formname,
             String contentType) {
        this.filename = filename;
        this.formname = formname;
         this.inStream = inStream;
         if (contentType != null) {
             this.contentType = contentType;
         }
    }
 
     public byte[] getData() {
         return data;
     }
 
     public void setData(byte[] data) {
        this.data = data;
     }

     public InputStream getInStream() {
         return inStream;
     }

     public void setInStream(InputStream inStream) {
         this.inStream = inStream;
     }
 
    public String getFilename() {
        return filename;
    }
 
     public void setFilename(String filename) {
         this.filename = filename;
     }
 
     public String getFormname() {
         return formname;
     }

     public void setFormname(String formname) {
         this.formname = formname;
     }
 
     public String getContentType() {
         return contentType;
     }

    public void setContentType(String contentType) {
         this.contentType = contentType;
     }
 }

 

 

 public class HttpUploadRequester {
    /**
     * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能: <FORM METHOD=POST
    * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"
      * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT
      * TYPE="text" NAME="id"> <input type="file" name="imagefile"/> <input
      * type="file" name="zip"/> </FORM>
    * 
     * @param actionUrl
      *            上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,
       *            你可以使用http://192.168.1.10:8080这样的路径测试)
       * @param params
      *            请求参数 key为参数名,value为参数值
       * @param file
       *            上传文件
       */
      // http协议中分割符,随便定义
      private static final String HTTP_BOUNDARY = "---------9dx5a2d578c2";
      private static final String MULTIPART_FORM_DATA = "multipart/form-data";
      private static final String LINE_ENTER = "\r\n"; // 换行 回车
      private static final int RESPONSE_OK = 200;
 
      public static String post(String urlPath, Map<String, String> params,
             FormFile[] formFiles) {
         try {
              URL url = new URL(urlPath);
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setRequestMethod("POST");
              conn.setReadTimeout(5 * 1000);
              conn.setDoOutput(true); // 发送POST请求, 必须设置允许输出
              conn.setUseCaches(false);
             conn.setRequestProperty("Connection", "Keep-Alive"); // 维持长链接
             conn.setRequestProperty("Charset", "UTF-8");
             conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
                     + "; boundary=" + HTTP_BOUNDARY);

            StringBuilder formItemData = new StringBuilder();
             // 构建 表单字段内容
           for (Map.Entry<String, String> entry : params.entrySet()) {
                 formItemData.append("--");
                 formItemData.append(HTTP_BOUNDARY);
                 formItemData.append(LINE_ENTER);
                formItemData.append("Content-Disposition: form-data; name=\""
                       + entry.getKey() + "\"\r\n\r\n");
                 formItemData.append(entry.getValue());
                 formItemData.append(LINE_ENTER);
            }
             DataOutputStream outStream = new DataOutputStream(
                   conn.getOutputStream());
            // 发送表单字段内容到服务器
             outStream.write(formItemData.toString().getBytes());
 
             // 发送上传文件数据
           for (FormFile fileData : formFiles) {
                 StringBuilder fileSplit = new StringBuilder();
                 fileSplit.append("--");
                 fileSplit.append(HTTP_BOUNDARY);
                 fileSplit.append(LINE_ENTER);
                fileSplit.append("Content-Disposition: form-data;name=\""
                        + fileData.getFormname() + "\";filename=\""
                        + fileData.getFilename() + "\"\r\n");
                fileSplit.append("Content-Type:" + fileData.getContentType()
                         + LINE_ENTER + LINE_ENTER);
                 outStream.write(fileSplit.toString().getBytes());

                 if (fileData.getInStream() != null) {
                     byte[] buffer = new byte[1024];
                     int length = 0;
                     while ((length = fileData.getInStream().read()) != -1) {
                        outStream.write(buffer, 0, length);
                     }
                    fileData.getInStream().close();
               } else {
                     outStream.write(fileData.getData(), 0,
                             fileData.getData().length);
                 }
                 outStream.write(LINE_ENTER.getBytes());
             }
             // 数据结束标志
            byte[] endData = ("--" + HTTP_BOUNDARY + "--" + LINE_ENTER)
                     .getBytes();
            outStream.write(endData);
             outStream.flush();
             outStream.close();
            int responseCode = conn.getResponseCode();
             if (responseCode != RESPONSE_OK) {
               throw new RuntimeException("请求url失败");
             }
             InputStream is = conn.getInputStream();
             int ch;
             StringBuilder b = new StringBuilder();
            while ((ch = is.read()) != -1) {
                 b.append((char) ch);
           }
            Log.i("HttpPost", b.toString());
             conn.disconnect();
             return b.toString();
        } catch (Exception e) {
            throw new RuntimeException();
       }
     }
 
   // 上传单个文件
   public static String post(String urlPath, Map<String, String> params,
             FormFile formFiles) {
         return post(urlPath, params, new FormFile[] { formFiles });
     }
}

 

 // 以表单方式发送请求
 
         public static void sendDataToServerByForm() throws Exception {
 
                     Map<String, String> params = new HashMap<String, String>();
 
                 params.put("method", "sendDataByForm");

                   params.put("strData", "字符串数据");
 
                    // 获取SDCard中的good.jpg
 
                    File file = new File(Environment.getExternalStorageDirectory(),

                                      "app_Goog_Android_w.png");
 
                    FormFile fileData = new FormFile("app_Goog_Android_w.png", new FileInputStream(file),

                                    "fileData", "application/octet-stream");
 
                   HttpUploadRequester.post(

                                     "http://192.168.0.2:8080/AndroidWebServer/server.do", params,

                                      fileData);

          }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值