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章:绘图 =================================== ...
随机推荐
- 每日英语:A Chinese Father’s Most Important Job
When it comes to parenting, Chinese fathers say the most important role they play is that of the fam ...
- 【Socket】linux下http服务器开发
1.mystery引入 1)超文本传输协议(HTTP)是一种应用于分布式.合作式.多媒体信息系统的应用层协议 2)工作原理 1)客户端一台客户机与服务器建立连接后,会发送一个请求给服务器,请求方式的格 ...
- 使用 IDEA 开发工具(版本为 IntelliJ IDEA 14.1.4)打可执行jar包的操作步骤
声明:教程演示使用的开发工具的版本是 IntelliJ IDEA 14.1.4. 1.选择IDEA开发工具菜单栏 File --> Project Structure,弹出如下窗口,在左侧的列表 ...
- php implode
implode() 函数返回由数组元素组合成的字符串. <?php $arr = array('Hello','World!','I','love','Shanghai!'); echo imp ...
- json数据在前端(javascript)和后端(php)转换
学习目的:前后端数据交换 思路: json数据格式是怎么样? 后端各种语言怎么将自己内容转换成json格式的内容? 前端怎么接收json数据?有几种方式? js中怎么将json数据转换成js中的数 ...
- 深入理解IoC和DI
本文章转载自: https://segmentfault.com/a/1190000005602011 最近在研究php的lumen框架和phalcon框架,这两个框架的底层架构都用到了IoC,DI, ...
- Java实现图片添加水印
参考别人的感觉挺好玩,还没仔细研究,先上代码. package WaterMark; import javax.imageio.ImageIO; import java.awt.*; import j ...
- C语言 · 选最大数
算法提高 选最大数 时间限制:1.0s 内存限制:512.0MB 输入3个整数a.b.c,(数的范围是[1,10000])输出其中最大的数.(用指针实现) 样例输入 2 5 1 样例 ...
- Eclipse源代码分析
Eclipse源代码分析 一.概述走入Eclipse的内核,看看它到底是怎么工作的? 1.Eclipse源代码 下载地址:http://download.eclipse.org/eclipse/dow ...
- Eclipse 下安装 SVN的方法
http://welcome66.iteye.com/blog/1845176 eclipse里安装SVN插件,一般来说,有两种方式: 直接下载SVN插件,将其解压到eclipse的对应目录里 使用e ...