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. 6月17 ThinkPHP连接数据库------数据的修改及删除

    1.数据修改操作 save()  实现数据修改,返回受影响的记录条数 具体有两种方式实现数据修改,与添加类似(数组.AR方式) 1.数组方式 a)         $goods = D(“Goods” ...

  2. 【Python】Anaconda配置

    Anaconda 是一个用于科学计算的Python发行版,支持 Linux.Mac.Windows 系统,提供了包管理与环境管理的功能,可以很方便地解决多版本 Python 并存.切换以及各种第三方包 ...

  3. [luogu P2324] [SCOI2005]骑士精神

    [luogu P2324] [SCOI2005]骑士精神 题目描述 输入输出格式 输入格式: 第一行有一个正整数T(T<=10),表示一共有N组数据.接下来有T个5×5的矩阵,0表示白色骑士,1 ...

  4. ORA-01034: ORACLE not available ORA-27101

    出现ORA-01034和ORA-27101的原因是多方面的:主要是oracle当前的服务不可用,shared memory realm does not exist,是因为oracle没有启动或没有正 ...

  5. vijos 清点人数

    背景 NK中学组织同学们去五云山寨参加社会实践活动,按惯例要乘坐火车去.由于NK中学的学生很多,在火车开之前必须清点好人数. 描述 初始时,火车上没有学生:当同学们开始上火车时,年级主任从第一节车厢出 ...

  6. numpy ndarray

    >>> aarray([[1, 2], [3, 4]])>>> a.shape(2, 2)>>> barray([2, 3])>>&g ...

  7. java 一些容易忽视的小点-控制语句

    随机数 .Math.random()该方法用于产生一个0到1区间的double类型的随机数,但是不包括1 if-else循环语句 如果if语句不写{},则只能作用于后面的第一条语句 switch语句 ...

  8. window有哪写事件?

    onload:加载事件网页加载完毕后执行. onscroll:滚动事件. onresize:窗口缩放事件.

  9. js中有哪几种函数?

    匿名函数,回调函数,递归函数,构造函数

  10. [Codeforces721E]Road to Home

    Problem 有一条长为l的公路(可看为数轴),n盏路灯,每盏路灯有照射区间且互不重叠. 有个人要走过这条公路,他只敢在路灯照射的地方唱歌,固定走p唱完一首歌,歌曲必须连续唱否则就要至少走t才能继续 ...