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. jython 2.7 b3发布

    Jython 2.7b3 Bugs Fixed - [ 2108 ] Cannot set attribute to instances of AST/PythonTree (blocks pyfla ...

  2. 线段树---Atlantis

    题目网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=110064#problem/A Description There are se ...

  3. 浅谈一下缓存策略以及memcached 、redis区别

    缓存策略三要素:缓存命中率   缓存更新策略  最大缓存容量.衡量一个缓存方案的好坏标准是:缓存命中率.缓存命中率越高,缓存方法设计的越好. 三者之间的关系为:当缓存到达最大的缓存容量时,会触发缓存更 ...

  4. javascript中的defer是什么?

    今天看到stackoverflow上的这样一个问题(问题链接),大概是说用jQuery获取不到元素,这是我们刚开始接触javascript常常会碰到的问题,回答者列举了4中方法去解决获取不到元素的问题 ...

  5. 任意类型转换为IntPtr

    之前,将数组.结构体等转换为IntPtr使用的是Marshal.Copy().Marshal.StructureToPtr(),但是有个问题自定义的结构体数组没法这样转化,一般网上给出的解决方法就是通 ...

  6. Mybatis学习记录(八)----Mybatis整合Spring

    1.整合思路 需要spring通过单例方式管理SqlSessionFactory. spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession.(sp ...

  7. [leetcode] Rectangle Area

    Rectangle Area Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectang ...

  8. 内存管理2(主讲MRR)

    内存管理2 我们讨论过properties 后,所有的内存管理系统都是通过控制所有对象的生命周期来减少内存的占用.iOS和OS X应用程序完成这些是通过对象拥有者来实现的,它保证了只要对象使用就会存在 ...

  9. iOS设计模式之原型模式

    原型模式 基本理解 原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象. 原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节 ...

  10. Web应用程序系统的多用户权限控制设计及实现-用户模块【7】

    前五章均是从整体上讲述了Web应用程序的多用户权限控制实现流程,本章讲述Web权限管理系统的基本模块-用户模块.用户模块涉及到的数据表为用户表. 1.1用户域 为了更规范和方便后期系统的二次开发和维护 ...