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. java getInstance()的使用

    转自:https://www.cnblogs.com/roadone/p/7977544.html 对象的实例化方法,也是比较多的,最常用的方法是直接使用new,而这是最普通的,如果要考虑到其它的需要 ...

  2. leetcode-algorithms-19 Remove Nth Node From End of List

    leetcode-algorithms-19 Remove Nth Node From End of List Given a linked list, remove the n-th node fr ...

  3. CO15批次确定,标准的太蛋疼了

    1.批次确定的配置,之前有转过,自己也动手配过,可以是可以,但是蛋疼,用户不愿意去弹出的界面选批次...2.因为这边的批次全部是按年月日+流水生成的,所以在批次确定这里就需要按照批次的号来排序选择了 ...

  4. NIO高性能框架-Netty

    一:Netty是什么 ? Netty是目前最流行的由JBOSS提供的一个Java开源框架NIO框架,Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客 ...

  5. 平面最近点对模板[luogu P1429]

    %:pragma GCC optimize() #include<bits/stdc++.h> #define DB double #define m (((l)+(r))>> ...

  6. 十一、持久层框架(MyBatis)

    一.基于注解方式的CRUD 把xml方式的CRUD修改为注解方式 之前在xml中配置,是在<mapper></mapper>标签下写CRUD <mapper namesp ...

  7. 学习建一个spring-Mvc项目

    学习建一个spring-Mvc项目 首先要有jdk1.8以上,spring,mybatis,以及整合jar包,tomcat ,然后配置环境(前面有配置得方法). 1)右键new project,--& ...

  8. WannaCry(永恒之蓝)病毒处理方法

    1.直接关闭server服务 打开cmd执行关闭server服务即可: net stop server 控制面板--管理工具--服务里手动关掉 2.防火墙限制445端口 3.打补丁 [KB401259 ...

  9. vsftp的安装与配置

    1.安装 直接使用yum安装,如果没有网络在其他机器使用yum先离线下载即可,vsftpd一般就自己不需要装其他依赖包 rpm -qa|grep vsftpd #查看是否安装 yum install ...

  10. paysoft 网关出现EntityRef:expecting;的错误。

    paysoft 网关出现EntityRef:expecting;的错误. 原因是传进去的url里有&字符,之前是自动转义的,现在要手工改成& http://www.runoob.com ...