HttpURLConnection发送POST请求(可包含文件)
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map; /**
* HttpURLConnection发送Post请求工具类
*
* @author pang
*
*/
public class HttpURLConnectionPost { /**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param actionUrl
* 访问的服务器URL
* @param params
* 普通参数
* @param files
* 文件参数
* @return
* @throws IOException
*/
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws Exception { StringBuilder sb2 = new StringBuilder();
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) {
// 读取返回数据
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8")); //$NON-NLS-1$
String line = null;
while ((line = reader.readLine()) != null) {
sb2.append(line).append("\n"); //$NON-NLS-1$
}
reader.close();
}
outStream.close();
conn.disconnect(); return sb2.toString();
} /**
* 以数据流的形式传参
*
* @param actionUrl
* @param params
* @param files
* @return
* @throws Exception
*/
public static String postFile(String actionUrl, Map<String, String> params,
Map<String, byte[]> files) throws Exception {
StringBuilder sb2 = new StringBuilder();
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=\"file\"; filename=\"" //$NON-NLS-1$
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type:" + "application/octet-stream;UTF-8"
+ LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes()); 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) {
// 读取返回数据
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8")); //$NON-NLS-1$
String line = null;
while ((line = reader.readLine()) != null) {
sb2.append(line).append("\n"); //$NON-NLS-1$
}
reader.close();
}
outStream.close();
conn.disconnect(); return sb2.toString();
} public static byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String Default_Address = "http://192.168.21.106:8080/ideweb/noSessionAndSecurity_submitBug.do";
try {
Map<String, String> requestParamsMap = new HashMap<String, String>();
requestParamsMap.put("userName", "huadoumi");
requestParamsMap.put("desp",
"<h1>123 321</h1>");
requestParamsMap.put("fileName", "zzz.txt");
requestParamsMap.put("productId", "AFAIDE"); // Map<String, byte[]> files = new HashMap<String, byte[]>();
// byte[] bytes = getContent("E:" + File.separator + "hello.txt");
// files.put("zzz.txt", bytes);
// String a = postFile(Default_Address, requestParamsMap, files);
// System.out.println(a); Map<String, File> files = new HashMap<String, File>();
File file = new File("E:" + File.separator + "hello.txt");
files.put("aaa.txt", file);
String b = post(Default_Address, requestParamsMap, files);
System.out.println(b);
} catch (Exception e) {
e.printStackTrace();
}
} }
HttpURLConnection发送POST请求(可包含文件)的更多相关文章
- HttpURLConnection 发送http请求帮助类
java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...
- HttpUrlConnection发送url请求(后台springmvc)
1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...
- 利用HttpURLConnection发送post请求上传多个文件
本文要用java.net.HttpURLConnection来实现多个文件上传 1. 研究 form 表单到底封装了什么样的信息发送到servlet. 假如我参数写的内容是hello word,然后二 ...
- python发送post请求上传文件,无法解析上传的文件
前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...
- 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)
Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...
- Java利用原始HttpURLConnection发送http请求数据小结
1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...
- Java 利用HttpURLConnection发送http请求
写了一个简单的 Http 请求的Class,实现了 get, post ,postfile package com.asus.uts.util; import org.json.JSONExcepti ...
- 【react读取文件】react发送GET请求读取静态文件
react中,使用发送请求的方式把static文件夹中的前端可访问的静态文件读取成字符串: 1.new request,需要用到getRequestHeaders组件 2.fetch获取respons ...
- HttpURLConnection 发送PUT请求 json请求体 与服务端接收
发送请求: public void testHttp() { String result = ""; try { URL postURL = new URL("http: ...
随机推荐
- ref与out的区别
若要使用 ref 参数,方法定义和调用方法均必须显式使用 ref 关键字,如下面的示例所示. class RefExample { static void Method(ref int i) { // ...
- jquery实现全选功能
主要是模拟一些网页中的表格实现全选功能. <form> 你爱好的运动是: <input type="checkbox" id="Check" ...
- .NET开发 正则表达式中的 Bug
又发现了一个 .net 的 bug!最近在使用正则表达式的时候发现:在忽略大小写的时候,匹配值从 0xff 到 0xffff 之间的所有字符,正则表达式竟然也能匹配两个 ASCII 字符:i(code ...
- Scala underscore的用途
_ 的用途 // import all import scala.io._ // import all, but hide Codec import scala.io.{Codec => _, ...
- [小北De编程手记] : Lesson 01 - Selenium For C# 之 环境搭建
在我看来一个自动化测试平台的构建,是一种很好的了解开发语言,单元测试框架,自动化测试驱动,设计模式等等等的途径.因此,在下选择了自动化测试的这个话题来和大家分享一下本人关于软件开发和自动化测试的认识. ...
- Hazelcast介绍与使用
Hazelcast 是一个开源的可嵌入式数据网格(社区版免费,企业版收费).你可以把它看做是内存数据库,不过它与 Redis 等内存数据库又有些不同.项目地址:http://hazelcast.org ...
- basket.js 源码分析
basket.js 源码分析 一.前言 basket.js 可以用来加载js脚本并且保存到 LocalStorage 上,使我们可以更加精准地控制缓存,即使是在 http 缓存过期之后也可以使用.因此 ...
- C# Web Api 上传文件
一. 使用默认方法上传文件: 1.Action: /// <summary> /// 上传文件 使用上传后的默认文件名称 /// 默认名称是BodyPart_XXXXXX,BodyPart ...
- .NET破解之百度网盘批量转存工具
在百度网盘上看到好的资源,总想转存到自己的网盘,加以整理.由于分享的规则原因,手动转存非常麻烦,于是百度批量转存工具.最先搜到的是小兵的百度云转存助手,无需注册,试用版用户一次只能操作10个,而捐助用 ...
- 桥牌笔记:Skill Level 4 D8
西拿黑桃K.A后,转攻小方块. 看来只有一个小红桃失张了.飞方块没有必要冒险.但将牌分布4-0时会有点麻烦.