zoukankan      html  css  js  c++  java
  • Java通过HTTP POST请求上传文件示例

    概述:

    http请求在所有的编程语言中几乎都是支持的,我们常用的两种为:GET,POST请求。一般情况下,发送一个GET请求都很简单,因为参数直接放在请求的URL上,所以,对于PHP这种语言,甚至只需要一行:file_get_content(url);就能完成数据的获取,但对于POST请求,由于其数据是在消息体中发送出去的,所以相对来说要麻烦一点,再涉及到需要发送文件等二进制的数据类型,就更需要更多的处理,下面我们用Java语言来实现POST请求发送数据,其他语言类似。

    public class MainUI {
        
        private static final String REQUEST_PATH = "http://localhost/server_url.php";
        private static final String BOUNDARY = "20140501";
    
        /**
         * @param args
         * @throws Exception 
         */
        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
            
            URL url = new URL(REQUEST_PATH);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(3000); // 设置发起连接的等待时间,3s
            httpConn.setReadTimeout(30000); // 设置数据读取超时的时间,30s
            httpConn.setUseCaches(false); // 设置不使用缓存
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream os = httpConn.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            
            String content = "--" + BOUNDARY + "
    ";
            content       += "Content-Disposition: form-data; name="title"" + "
    
    ";
            content       += "我是post数据的值";
            content       += "
    --" + BOUNDARY + "
    ";
            content       += "Content-Disposition: form-data; name="cover_img"; filename="avatar.jpg"
    ";
            content       += "Content-Type: image/jpeg
    
    ";
            bos.write(content.getBytes());
            
            // 开始写出文件的二进制数据
            FileInputStream fin = new FileInputStream(new File("avatar.jpg"));
            BufferedInputStream bfi = new BufferedInputStream(fin);
            byte[] buffer = new byte[4096];
            int bytes = bfi.read(buffer, 0, buffer.length);
            while (bytes != -1) {
                bos.write(buffer, 0, bytes);
                bytes = bfi.read(buffer, 0, buffer.length);
            }
            bfi.close();
            fin.close();
            bos.write(("
    --" + BOUNDARY).getBytes());
            bos.flush();
            bos.close();
            os.close();
            
             // 读取返回数据  
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("
    ");
            }
            String res = strBuf.toString();
            System.out.println(res);
            reader.close();
            httpConn.disconnect();
        }
    
    }

    下面,对上述的代码做一些必要的说明:

    http发送的post数据是通过boundary和换行符来分割的,boundary是一个随机的字符串即可,但不要与你传递的参数名或参数值相同。

    换行符要求也是比较严格的,数据的声明和数据的值之间需要两个换行符,两个数据之间要用boundary来划分。对于二进制的数据来说,只是参数的类型声明和普通的数据有点区别,比如上述的代码增加了filename和content-type,二进制的数据以字符流写出去就行了。

  • 相关阅读:
    轻松实现 网络视频播放器
    端口扫描 多方式协同实现
    关于部分应用无法向POJ提交代码的解决方案
    一套跨平台五子棋网游的开发经历
    SSH2.0编程 ssh协议过程实现
    ssh秘钥交换详解与实现 diffie-hellman-group-exchange-sha
    OnlineJudge 离线题库采集
    SOCKET 实现NAT 穿越
    基于公网smtp协议实现邮件服务器
    周六搞事情,微信小程序开发文档已放出!
  • 原文地址:https://www.cnblogs.com/shizqiang/p/5992134.html
Copyright © 2011-2022 走看看