Java使用HttpClient上传文件
Java可以使用HttpClient发送Http请求、上传文件等,非常的方便
Maven
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
上传代码1:
public static void upload2() throws ClientProtocolException, IOException{
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse httpResponse = null;
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
HttpPost httpPost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receiveFile.html");
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); //File file = new File("F:\\Ken\\1.PNG");
//FileBody bin = new FileBody(file); File file = new File("F:\\Ken\\abc.pdf"); //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
//当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
//multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
multipartEntityBuilder.addBinaryBody("file",file);
//multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
multipartEntityBuilder.addTextBody("comment", "this is comment");
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity); httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
int statusCode= httpResponse.getStatusLine().getStatusCode();
if(statusCode == 200){
BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
StringBuffer buffer = new StringBuffer();
String str = "";
while(!StringUtil.isRealEmpty(str = reader.readLine())) {
buffer.append(str);
} System.out.println(buffer.toString());
} httpClient.close();
if(httpResponse!=null){
httpResponse.close();
} }
上传代码2:
public static void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
//CloseableHttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receiveFile.html"); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
httppost.setConfig(requestConfig); FileBody bin = new FileBody(new File("F:\\Ken\\abc.pdf"));
StringBody comment = new StringBody("This is comment", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).addPart("comment", comment).build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseEntityStr = EntityUtils.toString(response.getEntity());
System.out.println(responseEntityStr);
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String post() throws ClientProtocolException, IOException{
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receivePost.html");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(22000).build();
httpPost.setConfig(requestConfig);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user.loginId", "Lin"));
params.add(new BasicNameValuePair("user.employeeName","令狐冲"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,Charset.forName("UTF-8"));
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null){
String content = EntityUtils.toString(responseEntity,"UTF-8");
System.out.println(content);
} if(httpResponse!=null){
httpResponse.close();
}
if(httpClient!=null){
httpClient.close();
}
return null;
}
Java使用HttpClient上传文件的更多相关文章
- 《手把手教你》系列技巧篇(五十四)-java+ selenium自动化测试-上传文件-中篇(详细教程)
1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...
- 《手把手教你》系列技巧篇(五十五)-java+ selenium自动化测试-上传文件-下篇(详细教程)
1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...
- java使用httpcomponents 上传文件
一.httpcomponents简介 httpcomponents 是apache下的用来负责创建和维护一个工具集的低水平Java组件集中在HTTP和相关协议的工程.我们可以用它在代码中直接发送htt ...
- Java使用HttpURLConnection上传文件
从普通Web页面上传文件非常easy.仅仅须要在form标签叫上enctype="multipart/form-data"就可以,剩余工作便都交给浏览器去完毕数据收集并发送Http ...
- Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...
- Java使用HttpURLConnection上传文件(转)
从普通Web页面上传文件很简单,只需要在form标签叫上enctype="multipart/form-data"即可,剩余工作便都交给浏览器去完成数据收集并发送Http请求.但是 ...
- java使用ftp上传文件
ftpServer是apache MINA项目的一个子项目,它实现了一个ftp服务器,与vsftpd是同类产品.Filezilla是一个可视化的ftp服务器. ftp客户端也有很多,如Filezill ...
- Java Servlet 接收上传文件
在Java中使用 Servlet 来接收用户上传的文件,需要用到两个apache包,分别是 commons-fileupload 和 commons-io 包: 如果直接在doPost中,使用requ ...
- [转]httpclient 上传文件、下载文件
用httpclient4.3 post方式推送文件到服务端 准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...
随机推荐
- 【IDEA】【5】快捷键
前言: 1,更改快捷键:File->Settings->Keymap 2,我自定义的快捷键 shitf+alt+s getter,setter,toString方法 (修改处:Keymap ...
- git:not a git repository (or any of the parent directories)
我用git add file添加文件时出现了这样错误: fatal: Not a git repository (or any of the parent directories): .git 提示说 ...
- ORACLE中ESCAPE关键字用法
ESCAPE用法 1.使用 ESCAPE 关键字定义转义符: 在模式中,当转义符置于通配符之前时,该通配符就解释为普通字符. 2.ESCAPE 'escape_character' 允许在字符串中搜 ...
- Redis+Twemproxy+HAProxy集群(转) 干货
原文地址:Redis+Twemproxy+HAProxy集群 干货 Redis主从模式 Redis数据库与传统数据库属于并行关系,也就是说传统的关系型数据库保存的是结构化数据,而Redis保存的是一 ...
- Javascript 将 HTML 页面生成 PDF 并下载
最近碰到个需求,需要把当前页面生成 pdf,并下载.弄了几天,自己整理整理,记录下来,我觉得应该会有人需要 :) html2canvas 简介 我们可以直接在浏览器端使用html2canvas,对整个 ...
- Python 正则实现计算器
# !/usr/bin/env/ python3 # -*- coding: utf-8 -*- """用户输入计算表达式,显示计算结果""" ...
- android 数据库添加字符串 添加失败 解决方案
这两天遇到一个棘手的问题,在往sqlite数据库中添加数据时,总是添加失败,但是添加数字却可以.原来是添加时,忘记添加''号修饰. 修改前: 修改后: 这样就完美解决.
- activity和fragment之前运行的生命周期
1.activity生命周期 2.fragment的生命周期 3.对比图 4.测试代码 package com.goso.testapp; import android.app.Activity; i ...
- CentOS查询系统版本
1.cat /proc/version 2.cat /etc/redhat-release 3.cat /proc/version 4.uname -a
- python两个字典合并,两个list合并
1.两个字典:a={'a':1,'b':2,'c':3} b= {'aa':11,'bb':22,'cc':33} 合并1:dict(a,**b) 操作如下: 合并2:dict(a.items()+ ...