HttpURLConnection 发送 文件和字符串信息
以文件的形式传参
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param actionUrl 访问的服务器URL
* @param params 普通参数
* @param files 文件参数
* @return
* @throws IOException
*/
public static void post(String actionUrl, 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(5 * 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);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
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());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null)
{
for (Map.Entry<String, File> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
// name是post中传参的键 filename是文件的名称
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);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
}
// return in.toString();
}
以数据流的形式传参
public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files)
throws Exception
{
StringBuilder sb2 = null;
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(6 * 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);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
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());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null)
{
for (Map.Entry<String, byte[]> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"pic\"; 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);
// }
// is.close();
outStream.write(file.getValue());
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
System.out.println(sb2.toString());
}
outStream.close();
conn.disconnect();
// 解析服务器返回来的数据
return ParseJson.getEditMadIconResult(sb2.toString());
}
else
{
return "Update icon Fail";
}
// return in.toString();
}
HttpURLConnection 发送 文件和字符串信息的更多相关文章
- httpclient 发送文件和字符串信息
HttpPost httpPost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntit ...
- httpurlconnection发送文件到服务端并接收
httpurlconnection发送文件到服务端并接收 客户端 import java.io.DataInputStream; import java.io.File; import java.io ...
- HttpURLConnection发送POST请求(可包含文件)
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...
- [转]C#网络编程(订立协议和发送文件) - Part.4
本文转自:http://www.tracefact.net/CSharp-Programming/Network-Programming-Part4.aspx 源码下载:http://www.trac ...
- socket(TCP)发送文件
一:由于在上一个随笔的基础之上拓展的所以直接上代码,客户端: using System; using System.Collections.Generic; using System.Componen ...
- C#_Socket网络编程实现的简单局域网内即时聊天,发送文件,抖动窗口。
最近接触了C#Socket网络编程,试着做了试试(*^__^*) 实现多个客户端和服务端互相发送消息 发送文件抖动窗口功能 服务端: using System; using System.Collec ...
- Smack+Openfire 接收和发送文件
转载请注明出处:http://blog.csdn.net/steelychen/article/details/37958839 发送文件须要提供准确的接收放username称(例:user2@192 ...
- cookie 就是一些字符串信息
什么是 Cookie “cookie 是存储于访问者的计算机中的变量.每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie.你可以使用JavaScript 来创建和取回cookie 的 ...
- R语言编程艺术(4)R对数据、文件、字符串以及图形的处理
本文对应<R语言编程艺术> 第8章:数学运算与模拟: 第10章:输入与输出: 第11章:字符串操作: 第12章:绘图 =================================== ...
随机推荐
- 每日英语:China's Wistful Wen Gets His Wish
As his term as premier was drawing to a close, Wen Jiabao reflected wistfully on some of the goals h ...
- 设置模式之单例模式(附上一个Objective-C编写的播放音乐的单例类)
在查阅Cocoa Touch开发文档时,会发现框架中随处可见的大量单例类,比如说,UIApplication.NSFileManager 等. UIApplication 框架中极为常用的一个单例类, ...
- hdu3926(判断两个图是否相似,模版)
题意:给你2个图,最大度为2.问两个图是否相似. 思路:图中有环.有链,判断环的个数以及每个环组成的人数,还有链的个数以及每个链组成的人数 是否相等即可. 如果形成了环,那么每形成一个环,结点数就会多 ...
- hdu1598
思路:对所有路径的速度从小到大排个序,然后枚举高度差就ok...... #include<iostream> #include<cstdio> #include<cstr ...
- ado ole方式访问access的两种方式
OleDbConnection Connection = new OleDbConnection(); OleDbDataAdapter adapter = null; //ConnectiongSt ...
- spark 数据倾斜的一些表现
spark 数据倾斜的一些表现 https://yq.aliyun.com/articles/62541
- Caused by: java.lang.IllegalStateException: Method has too many Body parameters
feign多参数问题1.1GET方式错误写法 @RequestMapping(value="/test", method=RequestMethod.GET) Model test ...
- react学习资源
http://www.ruanyifeng.com/blog/2015/03/react.html http://www.ruanyifeng.com/blog/2015/02/future-of-d ...
- linux比较两个文件是否一样(linux命令md5sum使用方法)
1.简介 MD5算法常常被用来验证网络文件传输的完整性,防止文件被人篡改.MD5 全称是报文摘要算法(Message-Digest Algorithm 5),此算法对任意长度的信息逐位进行计算,产生一 ...
- MQ调研梳理
1.架构 主项 子项 rabbitMQ rocketMQ Kafka Hippo Tube 高可用 1:镜像队列. 2:集群.master/slave机制. HA 同步双写和异步复制均支持 (同maf ...