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: ...
随机推荐
- Python基础:开篇
一.概述 Python基础 是对 Python(2.7版本)基本语法的要点总结,主要参考了以下资料: Python核心编程(第二版) Learning Python (3rd Edition) Pyt ...
- 【转载】JS获取屏幕大小
前些日子需要给项目的弹窗上面罩,因为项目左侧是树形菜单,右侧嵌套的iframe ,iframe 的内容不是固定大小,那么,面罩的大小也就不是固定的 因此,用到了JQuery获取当前页面的窗口大小,于是 ...
- 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解
[源码下载] 重新想象 Windows 8 Store Apps (36) - 通知: Tile 详解 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 通知 Tile ...
- LeetCode2:Median of Two Sorted Arrays
题目: There are two sorted arrays A and B of size m and n respectively. Find the median of the two sor ...
- [moka同学笔记]yii2.0表单的使用
1.创建model /biaodan.php <?php /** * Created by PhpStorm. * User: moka同学 * Date: 2016/08/05 * Tim ...
- mybatis 下划线转驼峰配置
一直以来,在sqlmap文件中,对于数据库中的下划线字段转驼峰,我们都是通过resultmap来做的,如下: <resultMap id="ISTableStatistics" ...
- MySQL Fabric 分片性能测试
苦逼的人生,开始了新一轮调研.这次是上面要看 MySQL Fabric 分片性能,好吧,开搞. 1 啥是 MySQL Fabric 其实就是一个Python进程和应用端的Connector的组合.来一 ...
- java.util.TimeZone 新加方法 getTimeZone(ZoneId zoneId) 导致的问题
最近接受的项目中用spring配置了一个TimeZone对象: <bean id ="timeZone4Job" class="java.util.TimeZone ...
- ArrayList 与 LinkedList
ArrayList:数组结构,插入删除的效率低,查询的效率较高. LinkedList:链接数据结构,插入删除的效率较高,查询的效率低. 两者的使用 ArrayList:适合用作添加数据,做查询. L ...
- CSS中的三种基本的定位机制
CSS 定位机制 CSS 有三种基本的定位机制:普通流.浮动和绝对定位. 一.普通流 除非专门指定,否则所有框都在普通流中定位.普通流中元素框的位置由元素在(X)HTML中的位置决定.块级元素从上到下 ...