Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
先上代码:
public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable {
String urlStr = MyServiceConfig.getUrl() + UPLOAD_URL;
String fileName = FileUtils.getFileName(formUrl);
long fileSize = getFileSize(formUrl);
String uri = UriComponentsBuilder.fromUriString(urlStr).queryParam("fileId", fileId).build().encode().toString();
logger.debug("文件上传请求路径:{}", uri);
// 获取文件输入流
InputStream in = getFileInputString(formUrl);
if (null != in) {
URL urlObj = new URL(uri);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("POST"); // 设置关键值,以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName + "\"\r\n");
if(!fileName.endsWith("mp4")){
sb.append("Content-Type:image/jpeg\r\n\r\n");
}else if(){
sb.append("Content-Type:video/mp4\r\n\r\n");
}
//未知文件类型,以流的方式上传
//sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream dataIn = new DataInputStream(in);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = dataIn.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
logger.debug("文件上传返回信息{}",strBuf.toString());
reader.close();
con.disconnect();
con = null;
} else {
throw new Throwable("获取文件流失败,文件下载地址url=" + formUrl);
}
}
// 获取文件大小
public InputStream getFileInputString(String formUrl) throws Throwable {
URL urlPath = new URL(formUrl);
HttpURLConnection conn = (HttpURLConnection) urlPath.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int status = conn.getResponseCode();
if (status == 200) {
return conn.getInputStream();
}
return null;
}
//获取文件大小
public long getFileSize(String formUrl) throws Throwable{
URL urlPath = new URL(formUrl);
HttpURLConnection conn = (HttpURLConnection)urlPath.openConnection();
conn.setConnectTimeout(downloadTimeout);
conn.setRequestMethod("GET");
int status = conn.getResponseCode();
if(status==200){
return conn.getContentLengthLong();
}
return 0;
}
public static String getFileName(String fileFullPath) {
fileFullPath = fileFullPath.replace("/", "\\");
return fileFullPath.substring(fileFullPath.lastIndexOf("\\") + 1,
fileFullPath.length());
}
public static String getFileNameWithoutSuffix(String fileFullPath) {
fileFullPath = fileFullPath.replace("/", "\\");
return fileFullPath.substring(fileFullPath.lastIndexOf("\\") + 1,
fileFullPath.lastIndexOf("."));
}
代码逻辑:
1、从访问文件的url中获取文件流和文件大小;
2、模拟http上传文件post请求;
1》.打开httpurlconnection连接,设置关键值:重点是设置请求方法post和设置不缓存;
2》.设置请求头,设置边界;重点是Content-Type;
3》.设置请求正文,比较复杂,参照代码;
4》.获取返回值;
二、使用httpClient4.4上传文件:
//上传实体文件
public static void upload(String url,String filePath) throws Exception{
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/62.0.3202.89 Safari/537.36");
httpPost.setHeader("Accept-Language","zh-cn,zh;q=0.5");
httpPost.setHeader("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.7");
httpPost.setHeader("Connection","keep-alive"); MultipartEntityBuilder mutiEntity = MultipartEntityBuilder.create();
File file = new File(filePath);
//File file = new File("C:\\Users\\\\Desktop\\20171002中士.mp4");
//mutiEntity.addTextBody("filename","1问题.mp4");
mutiEntity.addPart("file", new FileBody(file)); CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost.setEntity(mutiEntity.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String content = EntityUtils.toString(httpEntity);
System.out.println(content); }
上传文件流: 重点是mode的设置,这里卡了半天;
//上传文件流
public static void upload(String url,InputStream in) throws Exception{
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/62.0.3202.89 Safari/537.36");
httpPost.setHeader("Accept-Language","zh-cn,zh;q=0.5");
httpPost.setHeader("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.7");
httpPost.setHeader("Connection","keep-alive"); MultipartEntityBuilder mutiEntity = MultipartEntityBuilder.create();
//mutiEntity.addTextBody("filename","16有问题.mp4");
mutiEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mutiEntity.addBinaryBody("uploadFile", in, ContentType.create("multipart/form-data"), "16有问题.mp4"); CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost.setEntity(mutiEntity.build());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String content = EntityUtils.toString(httpEntity);
System.out.println(content); }
使用RestTemplate:
public static void uploadFile(String url,File file){
RestTemplate template = new RestTemplate();
ClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory();
template.setRequestFactory(clientFactory);
URI uri = UriComponentsBuilder.fromUriString(url).build().encode().toUri();
FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
//param.add("fileName", "问题.mp4");
org.springframework.http.HttpEntity<MultiValueMap<String, Object>> httpEntity = new org.springframework.http.HttpEntity<MultiValueMap<String, Object>>(param);
ResponseEntity<String> responseEntity = template.exchange(uri, HttpMethod.POST, httpEntity, String.class);
System.out.println("文件上传成功,返回:" + responseEntity.getBody());
}
RestTemplate上传文件流:不建议用
这个比较麻烦,先看代码吧;
public static void uploadFile(String url,InputStream in){
RestTemplate template = new RestTemplate();
ClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory();
template.setRequestFactory(clientFactory);
URI uri = UriComponentsBuilder.fromUriString(url).build().encode().toUri();
// InputStreamResource resource = new InputStreamResource(in);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", new MultipartFileResource(in, "test"));
//param.add("fileName", "问题.mp4");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
org.springframework.http.HttpEntity<MultiValueMap<String, Object>> httpEntity =
new org.springframework.http.HttpEntity<MultiValueMap<String, Object>>(param,headers);
List<HttpMessageConverter<?>> messageConverters = template.getMessageConverters();
for (int i = 0; i < messageConverters.size(); i++) {
HttpMessageConverter<?> messageConverter = messageConverters.get(i);
if ( messageConverter.getClass().equals(ResourceHttpMessageConverter.class) )
messageConverters.set(i, new ResourceHttpMessageConverterHandlingInputStreams());
}
ResponseEntity<String> responseEntity = template.exchange(uri, HttpMethod.POST, httpEntity, String.class);
System.out.println("文件上传成功,返回:" + responseEntity.getBody());
}
这是修改后的,添加了转换器,因为添加之前会报错,文件流读了两次,其中一次是读取文件大小contentLength;
package com.my.upload; import java.io.IOException;
import java.io.InputStream; import org.springframework.core.io.InputStreamResource; public class MultipartFileResource extends InputStreamResource { private final String filename; public MultipartFileResource(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
@Override
public String getFilename() {
return this.filename;
} @Override
public long contentLength() throws IOException {
return -1; // we do not want to generally read the whole stream into memory ...
}
} package com.my.upload; import java.io.IOException; import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ResourceHttpMessageConverter; public class ResourceHttpMessageConverterHandlingInputStreams extends ResourceHttpMessageConverter { @Override
protected Long getContentLength(Resource resource, MediaType contentType) throws IOException {
Long contentLength = super.getContentLength(resource, contentType); return contentLength == null || contentLength < 0 ? null : contentLength;
}
}
以上!
Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)的更多相关文章
- java模拟浏览器上传文件
public static void main(String[] args) { String str = uploadFile("C:/Users/RGKY/Desktop/wKgBHVb ...
- ApiPost接口调试工具模拟Post上传文件(中文版Postman)
ApiPost简介: ApiPost是一个支持团队协作,并可直接生成文档的API调试.管理工具.它支持模拟POST.GET.PUT等常见请求,是后台接口开发者或前端.接口测试人员不可多得的工具 . A ...
- c# 模拟POST上传文件到服务器
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...
- 《手把手教你》系列技巧篇(五十四)-java+ selenium自动化测试-上传文件-中篇(详细教程)
1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...
- 《手把手教你》系列技巧篇(五十五)-java+ selenium自动化测试-上传文件-下篇(详细教程)
1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...
- java模拟form上传数据
Java模拟form表单上传 查看form表单提交的http请求为 import java.io.*; import java.net.*; public class FileUpload { /** ...
- java使用httpcomponents 上传文件
一.httpcomponents简介 httpcomponents 是apache下的用来负责创建和维护一个工具集的低水平Java组件集中在HTTP和相关协议的工程.我们可以用它在代码中直接发送htt ...
- Java Servlet 接收上传文件
在Java中使用 Servlet 来接收用户上传的文件,需要用到两个apache包,分别是 commons-fileupload 和 commons-io 包: 如果直接在doPost中,使用requ ...
- 通过WebClient模拟post上传文件到服务器
写在前面 最近一直在研究sharepoint的文档库,在上传文件到文档库的过程中,需要模拟post请求,也查找了几种模拟方式,webclient算是比较简单的方式. 一个例子 这里写一个简单接受pos ...
随机推荐
- scala写算法-List、Stream、以及剑指Offer里部分题目基于scala解法
Stream(immutable) Stream是惰性列表.实现细节涉及到lazy懒惰求值.传名参数等等技术(具体细节详见维基百科-求值策略). Stream和List是scala中严格求值和非严格求 ...
- JavaWeb之原生数据库连接
我们在开发JavaWeb项目时,常会需要连接数据库.我们以MySQL数据库为例,IDE工具为eclipse,讲述数据库连接与基本操作. 第一步,我们在Web项目的WebContent中建一个简单的前端 ...
- 入门级Nginx反向代理nodejs
本着想实现前后端分离开发的初衷,我决定学习一下关于nignx反向代理的配置. 1.下载Nginx稳定版本 2.打开nginx配置文件 nginx.conf: 3.在http模块的server部分配置 ...
- Effective Java 第三版——12. 始终重写 toString 方法
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Raspberry Pi中可用的Go IDE:liteide
p { margin-bottom: 0.25cm; line-height: 120% } a:link { } Raspberry Pi中可用的Go IDE:liteide p { margin- ...
- Java 字符编码与解码
1.字符编码的发展历程 ①.ASCII 码 因为计算机只认识数字,所以我们在计算机里面的一切数据都是以数字来表示,因为英文字符有限,所以规定使用的字节的最高位是 0,每一个字节都是以 0-127 之间 ...
- 关于HTTP协议头域详解
HTTP1.1 请求头:消息头 Accept:text/html,image/* 告诉服务器,客户机支持的数据类型 Accept-Charset:ISO-8859-1 告诉服务器,客户机采用的编 ...
- KD树
k-d树 在计算机科学里,k-d树( k-维树的缩写)是在k维欧几里德空间组织点的数据结构.k-d树可以使用在多种应用场合,如多维键值搜索(例:范围搜寻及最邻近搜索).k-d树是空间二分树(Binar ...
- 鸟哥的linux私房菜学习-(五)补充:重点回顾
为了避免瞬间断电造成的Linux系统危害,建议做为服务器的Linux主机应该加上不断电系统来持续提供稳定的电力: 默认的图形模式登陆中,可以选择语系以及作业阶段.作业阶段为多种窗口管理员软件所提供,如 ...
- Vue 爬坑之路(九)—— 用正确的姿势封装组件
迄今为止做的最大的 Vue 项目终于提交测试,天天加班的日子终于告一段落... 在开发过程中,结合 Vue 组件化的特性,开发通用组件是很基础且重要的工作 通用组件必须具备高性能.低耦合的特性 为了满 ...