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&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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请求(可包含文件)的更多相关文章

  1. HttpURLConnection 发送http请求帮助类

    java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...

  2. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  3. 利用HttpURLConnection发送post请求上传多个文件

    本文要用java.net.HttpURLConnection来实现多个文件上传 1. 研究 form 表单到底封装了什么样的信息发送到servlet. 假如我参数写的内容是hello word,然后二 ...

  4. python发送post请求上传文件,无法解析上传的文件

    前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...

  5. 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)

    Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...

  6. Java利用原始HttpURLConnection发送http请求数据小结

    1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...

  7. Java 利用HttpURLConnection发送http请求

    写了一个简单的 Http 请求的Class,实现了 get, post ,postfile package com.asus.uts.util; import org.json.JSONExcepti ...

  8. 【react读取文件】react发送GET请求读取静态文件

    react中,使用发送请求的方式把static文件夹中的前端可访问的静态文件读取成字符串: 1.new request,需要用到getRequestHeaders组件 2.fetch获取respons ...

  9. HttpURLConnection 发送PUT请求 json请求体 与服务端接收

    发送请求: public void testHttp() { String result = ""; try { URL postURL = new URL("http: ...

随机推荐

  1. C#基础--之数据类型

    C#基础--之数据类型 摘自:http://www.cnblogs.com/tonney/archive/2011/03/18/1987577.html 在第一章我们了解了C#的输入.输出语句后,我这 ...

  2. 泛函编程(19)-泛函库设计-Parallelism In Action

    上节我们讨论了并行运算组件库的基础设计,实现了并行运算最基本的功能:创建新的线程并提交一个任务异步执行.并行运算类型的基本表达形式如下: import java.util.concurrent._ o ...

  3. [PHP] 自定义错误处理

    关闭掉默认的错误提示,注册自己的错误提示 Application.php <?php class Application{ public static function main(){ head ...

  4. Linux下安装配置Nexus

    一.安装和运行nexus 1.下载nexus:http://www.sonatype.org/nexus/go 可选择tgz和zip格式,以及war,选择tgz或zip时不同版本可能在启动时存在一定问 ...

  5. ThoughtWorks西邮暑期特训营 -- JavaScript在线笔试题

    ThoughtWorks 公司在西邮正式开办的只教女生前端开发的女子卓越实验室已经几个月过去了,这次计划于暑期在西邮内部开展面向所有性别所有专业的前端培训. 具体官方安排请戳:ThoughtWorks ...

  6. 简单封装cookie操作

    1 //设置cookie 2 function setCookie(name, value, day) { 3 var oDate = new Date(); 4 oDate.setDate(oDat ...

  7. [Architecture Design] 跨平台架构设计

    [Architecture Design] 跨平台架构设计 跨越平台 Productivity Future Vision 2011 在开始谈跨平台架构设计之前,请大家先看看上面这段影片,影片内容是微 ...

  8. swift学习笔记之-函数

    //函数 import UIKit /*获得系统时间 var date = NSDate() var timeFormatter = NSDateFormatter() timeFormatter.d ...

  9. [ html canvas 模仿支付宝刮刮卡效果 ] canvas绘图属性 模仿支付宝刮刮卡效果实例演示

    <!DOCTYPE html> <html lang='zh-cn'> <head> <title>Insert you title</title ...

  10. C语言---文件

    1. 需要了解的概念 包括:数据流.缓冲区.文件类型.文件存取方式 1.1 数据流: 指程序与数据的交互是以流的形式进行的.进行C语言文件的存取时,都会先进行“打开文件”操作,这个操作就是在打开数据流 ...