【Java】POST简略
2015-07-14 21:26
423 查看
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); } }
相关文章推荐
- 获得spring容器上下文
- java高新技术上《九》
- java中的println方法打印Date类型数据
- [LeetCode][Java] Pow(x, n)
- Java源码---HashMap的底层实现
- java io流类图
- Eclipse设置:背景与字体大小和xml文件中字体大小调整
- java web如何根据用户使用的浏览器来提示用户更新或更换浏览器
- #笔记#圣思园 JavaWeb 第39讲——Filter过滤器
- JFinal所集成的插件们
- 在线java编辑器
- JAVA线程池的分析和使用
- Eclipse中jsp、js文件编辑时,卡死现象解决汇总
- java字符串常量池知识
- myEclipse8.5下SSH2开发时如何删除antlr-2.7.2包
- [LeetCode][Java] Anagrams
- Java自带的线程池ThreadPoolExecutor详细介绍说明和实例应用
- struts2中清空值栈中的值
- 通过Eclipse的Install New Software方式安装jbpm6
- 学习笔记java