Http请求之基于HttpUrlConnection,支持Header,Body传值,支持Multipart上传文件:
Http请求之基于HttpUrlConnection,支持Header,Body传值,支持Multipart上传文件:
- public static String post(String actionUrl, Map<String, String> headParams,
- Map<String, String> params,
- Map<String, File> files) throws IOException {
- String BOUNDARY = java.util.UUID.randomUUID().toString();
- String PREFIX = "--", LINEND = "\r\n";
- String MULTIPART_FROM_DATA = "multipart/form-data";
- String CHARSET = "UTF-8";
- URL uri = new URL(actionUrl);
- HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
- conn.setReadTimeout(30 * 1000); // 缓存的最长时间
- conn.setDoInput(true);// 允许输入
- conn.setDoOutput(true);// 允许输出
- conn.setUseCaches(false); // 不允许使用缓存
- conn.setRequestMethod("POST");
- conn.setRequestProperty("connection", "keep-alive");
- conn.setRequestProperty("Charsert", "UTF-8");
- conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
- + ";boundary=" + BOUNDARY);
- if(headParams!=null){
- for(String key : headParams.keySet()){
- conn.setRequestProperty(key, headParams.get(key));
- }
- }
- StringBuilder sb = new StringBuilder();
- if (params!=null) {
- // 首先组拼文本类型的参数
- for (Map.Entry<String, String> entry : params.entrySet()) {
- sb.append(PREFIX);
- sb.append(BOUNDARY);
- sb.append(LINEND);
- sb.append("Content-Disposition: form-data; name=\""
- + entry.getKey() + "\"" + LINEND);
- sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
- sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
- sb.append(LINEND);
- sb.append(entry.getValue());
- sb.append(LINEND);
- }
- }
- DataOutputStream outStream = new DataOutputStream(
- conn.getOutputStream());
- if (!TextUtils.isEmpty(sb.toString())) {
- outStream.write(sb.toString().getBytes());
- }
- // 发送文件数据
- if (files != null)
- for (Map.Entry<String, File> file : files.entrySet()) {
- StringBuilder sb1 = new StringBuilder();
- sb1.append(PREFIX);
- sb1.append(BOUNDARY);
- sb1.append(LINEND);
- sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
- + file.getKey() + "\"" + LINEND);
- sb1.append("Content-Type: application/octet-stream; charset="
- + CHARSET + LINEND);
- sb1.append(LINEND);
- outStream.write(sb1.toString().getBytes());
- InputStream is = new FileInputStream(file.getValue());
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = is.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- Log.i("HttpUtil", "写入中...");
- }
- is.close();
- outStream.write(LINEND.getBytes());
- }
- // 请求结束标志
- byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
- outStream.write(end_data);
- outStream.flush();
- Log.i("HttpUtil", "conn.getContentLength():"+conn.getContentLength());
- // 得到响应码
- int res = conn.getResponseCode();
- InputStream in = conn.getInputStream();
- if (res == 200) {
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
- StringBuffer buffer = new StringBuffer();
- String line = "";
- while ((line = bufferedReader.readLine()) != null){
- buffer.append(line);
- }
- // int ch;
- // StringBuilder sb2 = new StringBuilder();
- // while ((ch = in.read()) != -1) {
- // sb2.append((char) ch);
- // }
- return buffer.toString();
- }
- outStream.close();
- conn.disconnect();
- return in.toString();
- }

Http请求之基于HttpUrlConnection,支持Header,Body传值,支持Multipart上传文件:的更多相关文章
- 基于element ui 实现七牛云自定义key上传文件,并监听更新上传进度
借助上传Upload 上传组件的 http-request 覆盖默认的上传行为,可以自定义上传的实现 <el-upload multiple ref="sliderUpload&quo ...
- OkHttp上传文件,服务器端请求解析找不到文件信息的问题
长话短说,不深入解释了,官方给的上传案例代码: private static final String IMGUR_CLIENT_ID = "..."; private stati ...
- Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...
- php使用curl 实现GET和POST请求(抓取网页,上传文件),支持跨项目和跨服务器
一:curl 函数和参数详解 函数库:1:curl_init 初始化一个curl会话2:curl_close 关闭一个curl会话3:curl_setopt 为一个curl设置会话参数4:curl_e ...
- java http工具类和HttpUrlConnection上传文件分析
利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...
- JAVA模拟HTTP post请求上传文件
在开发中,我们使用的比较多的HTTP请求方式基本上就是GET.POST.其中GET用于从服务器获取数据,POST主要用于向服务器提交一些表单数据,例如文件上传等.而我们在使用HTTP请求时中遇到的比较 ...
- swagger上传文件并支持jwt认证
背景 由于swagger不仅提供了自动实现接口文档的说明而且支持页面调试,告别postman等工具,无需开发人员手动写api文档,缩减开发成本得到大家广泛认可 但是由于swagger没有提供上传文件的 ...
- android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件
AsyncHttpClient开源框架android-async-http还是非常方便的. AsyncHttpClient该类通经常使用在android应用程序中创建异步GET, POST, PUT和 ...
- django系列6--Ajax05 请求头ContentType, 使用Ajax上传文件
一.请求头ContentType ContentType指的是请求体的编码类型,常见的类型共有三种: 1.application/x-www-form-urlencoded 这应该是最常见的 POST ...
随机推荐
- sqlserver中的全局变量总结
@@CONNECTIONS返回自上次启动 Microsoft? SQL Server? 以来连接或试图连接的次数.@@CPU_BUSY返回自上次启动 Microsoft? SQL Server? 以来 ...
- java根据日期获取周几和获取某段时间内周几的日期
整理两个日期的方法. 根据日期获取当天是周几 /** * 根据日期获取当天是周几 * @param datetime 日期 * @return 周几 */ public static String d ...
- C# 在RichTextBox根据内容自动调整高度
private void richTextBox1_ContentsResized(object sender, ContentsResizedEventArgs e) { richTextB ...
- 【LOJ】#2670. 「NOI2012」随机数生成器
题解 矩阵乘法,注意需要快速乘 矩阵2*2 a c 0 1 代码 #include <iostream> #include <algorithm> #include <c ...
- 【AtCoder】ARC095 C-F题解
我居然每道题都能想出来 虽然不是每道题都能写对,debug了很久/facepalm C - Many Medians 排序后前N/2个数的中位数时排序后第N/2 + 1的数 其余的中位数都是排序后第N ...
- loadrunner 脚本中文乱码
loadrunner 脚本中文乱码 1.新建脚本--->选择协议(Http)-->选项-->高级-->选择“支持字符集”并点选“UTF-8”: 2.在回放脚本之前:Vuser- ...
- 003 python流程控制与函数
一:控制语句 1.条件语句 注意: if: elif: elif: else: 2.while循环 里面可以加else. # coding=utf-8 count=0 while count<3 ...
- hdoj2191 珍惜现在,感恩生活(01背包 || 多重背包)
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2191 思路 由于每种大米可能不止一袋,所以是多重背包问题,可以直接使用解决多重背包问题的方法,也可以将 ...
- JDK源码分析(一)——ArrayList
目录 ArrayList分析 ArrayList继承结构 ArrayList字段属性 ArrayList构造函数 重要方法 ArrayList Iterator迭代器 总结 ArrayList分析 ...
- Python使用正则
Python中使用正则的两种方式 在Python中有两只能够使用正则表达式的方式: 直接使用re模块中的函数 import re re_string = "{{(.*?)}}" s ...