java 上传MultipartFile和String post请求
/**
* POST Multipart Request
* @Description:
* @param requestUrl 请求url
* @param requestText 请求参数
* @param requestFile 请求上传的文件
* @return
* @throws Exception
*/
public String sendPost3(String requestUrl,
Map<String, String> requestText, Map<String, MultipartFile> requestFile) throws Exception{
HttpURLConnection conn = null;
InputStream input = null;
OutputStream os = null;
BufferedReader br = null;
StringBuffer buffer = null;
try {
URL url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(1000 * 10);
conn.setReadTimeout(1000 * 10);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data");
conn.setRequestProperty("Cookie", "sid=d696901c23409a695bb89caa67f38bd6;USER_FLAG_CHECK=d1281e431ec02361926042addd6e8244;pt_key=AAJdrsZRADAv-rYqAIae8TCpk15m92Ed0tNrhOrnxio7Zxd0PyWmR_eRNIrvKw9XUUrbNWqrzq4;appkey=wxshop_jstj;appid=wx805ef0a16c179341;");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.connect(); // 往服务器端写内容 也就是发起http请求需要带的参数
os = new DataOutputStream(conn.getOutputStream());
// 请求参数部分
writeParams(requestText, os);
// 请求上传文件部分
writeFile(requestFile, os);
// 请求结束标志
String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
os.write(endTarget.getBytes());
os.flush(); // 读取服务器端返回的内容
System.out.println("======================响应体=========================");
System.out.println("ResponseCode:" + conn.getResponseCode()
+ ",ResponseMessage:" + conn.getResponseMessage());
if(conn.getResponseCode()==200){
input = conn.getInputStream();
}else{
input = conn.getErrorStream();
} br = new BufferedReader(new InputStreamReader( input, "UTF-8"));
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
//......
System.out.println("返回报文:" + buffer.toString()); } catch (Exception e) {
//log.error(e.getMessage(), e);
throw new Exception(e);
} finally {
try {
if (conn != null) {
conn.disconnect();
conn = null;
} if (os != null) {
os.close();
os = null;
} if (br != null) {
br.close();
br = null;
}
} catch (IOException ex) {
//log.error(ex.getMessage(), ex);
throw new Exception(ex);
}
}
return buffer.toString();
} /**
* 对post参数进行编码处理并写入数据流中
* @throws Exception
*
* @throws IOException
*
* */
private static void writeParams(Map<String, String> requestText,
OutputStream os) throws Exception {
try{
String msg = "请求参数部分:\n";
if (requestText == null || requestText.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set<Map.Entry<String, String>> set = requestText.entrySet();
Iterator<Map.Entry<String, String>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
requestParams.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\"").append(LINE_END);
requestParams.append("Content-Type: text/plain; charset=utf-8")
.append(LINE_END);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINE_END);
requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
requestParams.append(entry.getValue());
requestParams.append(LINE_END);
}
os.write(requestParams.toString().getBytes());
os.flush(); msg += requestParams.toString();
} //System.out.println(msg);
}catch(Exception e){
//log.error("writeParams failed", e);
throw new Exception(e);
}
} /**
* 对post上传的文件进行编码处理并写入数据流中
*
* @throws IOException
*
* */
private static void writeFile(Map<String, MultipartFile> requestFile,
OutputStream os) throws Exception {
InputStream is = null;
try{
String msg = "请求上传文件部分:\n";
if (requestFile == null || requestFile.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set<Map.Entry<String, MultipartFile>> set = requestFile.entrySet();
Iterator<Map.Entry<String, MultipartFile>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, MultipartFile> entry = it.next();
if(entry.getValue() == null){//剔除value为空的键值对
continue;
}
requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
requestParams.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\"; filename=\"")
.append(entry.getValue().getName()).append("\"")
.append(LINE_END);
requestParams.append("Content-Type:")
.append(entry.getValue().getContentType())
.append(LINE_END);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINE_END);
requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容 os.write(requestParams.toString().getBytes());
os.write(entry.getValue().getBytes()); os.write(LINE_END.getBytes());
os.flush(); msg += requestParams.toString();
}
}
//System.out.println(msg);
}catch(Exception e){
//log.error("writeFile failed", e);
throw new Exception(e);
}finally{
try{
if(is!=null){
is.close();
}
}catch(Exception e){
//log.error("writeFile FileInputStream close failed", e);
throw new Exception(e);
}
}
}
java 上传MultipartFile和String post请求的更多相关文章
- java 上传文件到七牛云中
import com.alibaba.fastjson.JSONObject;import com.qiniu.common.QiniuException;import com.qiniu.commo ...
- 【java 上传+下载】
一.先说说上传 第一步:pom.xml文件 加上 上传文件依赖架包 <dependency> <groupId>commons-fileupload</groupId&g ...
- edtftpj让Java上传FTP文件支持断点续传
在用Java实现FTP上传文件功能时,特别是上传大文件的时候,可以需要这样的功能:程序在上传的过程中意外终止了,文件传了一大半,想从断掉了地方继续传:或者想做类似迅雷下载类似的功能,文件太大,今天传一 ...
- JAVA上传与下载
java下载指定地址的文件 package com.test; import java.io.FileNotFoundException; import java.io.FileOutputStrea ...
- Java上传文件FTP服务器代码
1. 在实际的应用重,通常是通过程序来进行文件的上传. 2. 实现java上传文件到ftp服务器中 新建maven项目 添加依赖 <dependency> <groupId>c ...
- java上传excel文件及解析
java上传excel文件及解析 CreateTime--2018年3月5日16:25:14 Author:Marydon 一.准备工作 1.1 文件上传插件:swfupload: 1.2 文件上 ...
- java 上传文件到 ftp 服务器
1. java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...
- java上传组件commons-fileupload的一些使用方法
在 http://www.apache.org,下载commons-fileupload-1.2.1.jar包,并把这个包加到工程中,以下是记录这个上传组件的一些使用方法. html测试页面,实现上传 ...
- element-ui上传组件,通过自定义请求上传文件
记录使用element-ui上传组件,通过自定义请求上传文件需要注意的地方. <el-upload ref="uploadMutiple" :auto-upload=&quo ...
随机推荐
- NX二次开发-UFUN初始化UF_initialize
在调用UFUN函数时必须加Uf.h头文件,代码开头和结尾加UF_initialize和UF_terminate NX9+VS2012 #include <uf.h> #include &l ...
- 执行SQL语句---INSERT/UPDATE/DELETE
1.执行SQL语句函数: int mysql_query(MYSQL* mysql, const char * query); query:所有的sql语句 2.例子: 向children表插入一条语 ...
- Always On主辅延迟相关描述
延迟是AlwaysOn最大的敌人之一 延迟是AlwaysON的最大敌人之一.对AlwaysON而言,其首要目标就尽量减少(无法避免)主副本.辅助副本的数据延迟,实现主副本.辅助副本的“数据同步”.只有 ...
- 秦曾昌人工智能课程---6、Decision Tree Learning
秦曾昌人工智能课程---6.Decision Tree Learning 一.总结 一句话总结: 怎样去构建决策树:比如一维:***|00|***|000|***,|为分割线,每个分割点都是一种情况, ...
- detours3.0文档翻译
拦截二进制函数 Detours库可以在运行过程中动态拦截函数调用.detours将目标函数前几个指令替换为一个无条件跳转,跳转到用户定义的detour函数.被拦截的函数保存在trampoline函数中 ...
- pure-ftpd 配置
# Disallow anonymous connections. Only allow authenticated users. NoAnonymous yes # If you want simp ...
- Codeforces 1154B Make Them Equal
题目链接:http://codeforces.com/problemset/problem/1154/B 题意:给定数组,可以给任意的的元素加上D 或者 减去D,如果能 使数组元素都相等,输出最小的D ...
- mybatis浅显认识
mybatis主配置文件: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configu ...
- python包下载路径
python所有包.模块镜像站 https://www.lfd.uci.edu/~gohlke/pythonlibs/
- mybatis 处理CLOB/BLOB类型数据
BLOB和CLOB都是大字段类型. BLOB是按二进制来存储的,而CLOB是可以直接存储文字的. 通常像图片.文件.音乐等信息就用BLOB字段来存储,先将文件转为二进制再存储进去.文章或者是较长的文字 ...