【Java】POST简略

原创
2015/07/14 21:26
阅读数 354

#POST上传文件

##简单描述:

post的数据在 request Payload 内, 因此,Request Headers 里面带有一个 boundary 属性,服务器收到 post 请求之后,通过 boundary 将参数从 Payload 中分离出来。

params = body.split(boundary)

唯一需要注意的是,CRLF(回车换行符)的使用。HTTP协议对CRLF的内容分割要求还是略严的。

##Request Headers

Content-Type:multipart/form-data; boundary=----WebKitFormBoundarydKY7YrWhI3bdiNYz

##Request Payload

--{boundary}
Content-Disposition: form-data; name="{name1}"

{value1}
--{boundary}
Content-Disposition: form-data; name="{name2}"

{value2}
--{boundary}
Content-Disposition: form-data; name="{file_name1}"; filename="xxx.png"
Content-Type: image/png

0x120x12...

--{boundary}--

##示例说明

<form method="post" enctype="multipart/form-data">
    <div><input type="checkbox" name="k1" checked value="1"/><label>1</label></div>
    <div><input type="checkbox" name="k1" checked value="2"/><label>2</label></div>
    <div><input type="file" name="pic"/></div>
</form>

提交格式:

headers

Content-Type:multipart/form-data; boundary=----WebKitFormBoundarydKY7YrWhI3bdiNYz

payload:

------WebKitFormBoundarydKY7YrWhI3bdiNYz
Content-Disposition: form-data; name="k1"

1
------WebKitFormBoundarydKY7YrWhI3bdiNYz
Content-Disposition: form-data; name="k2"

2
------WebKitFormBoundarydKY7YrWhI3bdiNYz
Content-Disposition: form-data; name="{file_name1}"; filename="xxx.png"
Content-Type: image/png

....(这里是图片字节).....

------WebKitFormBoundarydKY7YrWhI3bdiNYz--

#示例代码 import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;

public class Post {

    private String BOUNDARY = "-------1234567890987654321";
    private String CRLF = "\r\n";
    private Map<String, List<String>> keyValues = new HashMap<>();
    private Map<String, List<String>> pngs = new HashMap<>();

    //添加字符串键值对
    public void keyValue(String key, String value) {
        if (!keyValues.containsKey(key)) {
            keyValues.put(key, new ArrayList<>());
        }
        keyValues.get(key).add(value);
    }

    //添加png图片
    public void png(String key, String pngFilePath) {
        if (!pngs.containsKey(key)) {
            pngs.put(key, new ArrayList<>());
        }
        pngs.get(key).add(pngFilePath);
    }

    public String post(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(connection.getOutputStream());

            for (Map.Entry<String, List<String>> kv : keyValues.entrySet()) {
                for (String value : kv.getValue()) {
                    String item = new StringBuilder("--").append(BOUNDARY).append(CRLF)
                            .append("Content-Disposition: form-data; name=").append(kv.getKey()).append(CRLF)
                            .append(CRLF)
                            .append(value).append(CRLF)
                            .toString();
                    out.write(item.getBytes());
                }
            }

            //添加png图片
            for (Map.Entry<String, List<String>> kv : pngs.entrySet()) {
                for (String value : kv.getValue()) {
                    String item = new StringBuilder("--").append(BOUNDARY).append(CRLF)
                            .append("Content-Disposition: form-data; name=").append(kv.getKey()).append(";").append("filename=").append(value).append(CRLF)
                            .append("Content-Type: image/png").append(CRLF)
                            .append(CRLF)
                            .toString();
                    out.write(item.getBytes());

                    //写入文件内容
                    FileInputStream fileInputStream = new FileInputStream(value);
                    byte[] bytes = new byte[512];
                    int count;
                    while ((count = fileInputStream.read(bytes)) != -1) {
                        out.write(bytes, 0, count);
                    }
                    out.write(CRLF.getBytes());
                }
            }
            out.write(("--" + BOUNDARY + "--" + CRLF).getBytes());//结尾

            out.flush();
            out.close();

            StringBuffer response = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line).append("\n");
            }
            reader.close();
            return response.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) throws IOException {

        Post post = new Post();
        post.keyValue("k1", "a");
        post.keyValue("k2", "b");
        post.png("pic", "/home/xe/Pictures/1.png");
        post.png("pic", "/home/xe/Pictures/1.png");

        String response = post.post("http://127.0.0.1:3000/upload");
        System.out.println(response);
    }
}
展开阅读全文
打赏
0
11 收藏
分享
加载中
更多评论
打赏
0 评论
11 收藏
0
分享
返回顶部
顶部