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();
}
}
}
普通POST请求
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上传文件的更多相关文章

  1. 《手把手教你》系列技巧篇(五十四)-java+ selenium自动化测试-上传文件-中篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  2. 《手把手教你》系列技巧篇(五十五)-java+ selenium自动化测试-上传文件-下篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  3. java使用httpcomponents 上传文件

    一.httpcomponents简介 httpcomponents 是apache下的用来负责创建和维护一个工具集的低水平Java组件集中在HTTP和相关协议的工程.我们可以用它在代码中直接发送htt ...

  4. Java使用HttpURLConnection上传文件

    从普通Web页面上传文件非常easy.仅仅须要在form标签叫上enctype="multipart/form-data"就可以,剩余工作便都交给浏览器去完毕数据收集并发送Http ...

  5. Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)

    先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...

  6. Java使用HttpURLConnection上传文件(转)

    从普通Web页面上传文件很简单,只需要在form标签叫上enctype="multipart/form-data"即可,剩余工作便都交给浏览器去完成数据收集并发送Http请求.但是 ...

  7. java使用ftp上传文件

    ftpServer是apache MINA项目的一个子项目,它实现了一个ftp服务器,与vsftpd是同类产品.Filezilla是一个可视化的ftp服务器. ftp客户端也有很多,如Filezill ...

  8. Java Servlet 接收上传文件

    在Java中使用 Servlet 来接收用户上传的文件,需要用到两个apache包,分别是 commons-fileupload 和 commons-io 包: 如果直接在doPost中,使用requ ...

  9. [转]httpclient 上传文件、下载文件

    用httpclient4.3 post方式推送文件到服务端  准备:httpclient-4.3.3.jar:httpcore-4.3.2.jar:httpmime-4.3.3.jar/** * 上传 ...

随机推荐

  1. Matlab-10:Ritz-Galerkin方法求解二阶常微分方程

    一.代数多项式法: tic; clear clc % N=input('please key in the value of ''N'''); N=10; M=100; h=1/M; X=0:h:1; ...

  2. 【IDEA】【8】上传已有项目到Git

    问题:开发初期没有建立GIT仓库,开发一段时间后,需要将已有代码上传到Git 解决方案: 1,首先使用Git命令行 git clone XXXXX.git 将项目下载 2,拷贝下载下来的项目根目录下的 ...

  3. java骰子求和算法

    //扔 n 个骰子,向上面的数字之和为 S.给定 Given n,请列出所有可能的 S 值及其相应的概率public class Solution { /** * @param n an intege ...

  4. java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

    java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). at co ...

  5. mysql索引类型和方式

    索引 数据库的索引就像一本书的目录,能够加快数据库的查询速度. MYSQL索引有四种PRIMARY.INDEX.UNIQUE.FULLTEXT, 其中PRIMARY.INDEX.UNIQUE是一类,F ...

  6. win7下使用U盘安装双系统(Ubuntu-17)

    1.首先下载Ubuntu镜像文件,下载地址:http://mirrors.neusoft.edu.cn/ 2.下载 U盘操作系统安装工具- Universal USB Installer ,下载地址: ...

  7. 使用 NumPy 和 Matplotlib 绘制函数图

    Numpy是用python进行科学计算的基本程序包. 它主要包含以下功能: ♦强大的n维数组对象 ♦复杂(广播)函数工具 ♦用于集成c/c++和Fortran代码-有用的线性代数 ♦傅里叶变换和随机数 ...

  8. TCP/UDP工作流程图

     说到socket必须要贴的图: TCP工作流程:  UDP工作流程:

  9. Linux运维工程师真实的工作状态到底是怎么样的?

    现在的运维工程师在大家眼中是个什么样子呢? 是不是还是把服务器搬来搬去,每天不是在拿着Linux光盘开始装系统,就是在等待系统安装完成.你如果还是这么想,那就大错特错了.现在又有做一个新的物种诞生,那 ...

  10. Unity中DOTween插件的DOTweenPath轨迹移动

    先来看一下DOTweenPath组件的截图 1.Scene View Commands (1)SHIFT+CTRL:add a waypoint        加一个轨迹点 (2)SHIFT+ALT: ...