分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

HttpClient(五)-- 模拟表单上传文件

发布时间:2023-09-06 01:11责任编辑:白小东关键词:暂无标签

1.maven依赖

 ?????<dependency> ???????<groupId>org.apache.httpcomponents</groupId> ???????<artifactId>httpclient</artifactId> ???????<version>4.5.2</version> ???</dependency> ???????<dependency> ???????<groupId>org.apache.httpcomponents</groupId> ???????<artifactId>httpmime</artifactId> ???????<version>4.5.2</version> ???</dependency>

2.代码实现

import java.io.File;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class HttpClientUpload { ???public static void main(String[] args) { ???????// 将 fileUrl 上传到 url中,上传成功后,返回 下载地址 ???????String url = "http://127.0.0.1:8080/Joe/upload"; ???????String fileUrl = "C:/abc.txt"; ???????try { ???????????System.out.println(post(url, "file", new File(fileUrl))); ???????} catch (Exception e) { ???????????e.printStackTrace(); ???????} ???} ???/** ????* post:(上传). ????* ?????* @author Joe Date:2017年9月11日下午5:37:46 ????* @param serverUrl ????* @param fileParamName ????* @param file ????* @return ????* @throws ClientProtocolException ????* @throws IOException ????*/ ???public static String post(String serverUrl, String fileParamName, File file) ???????????throws ClientProtocolException, IOException { ???????HttpPost httpPost = new HttpPost(serverUrl); ???????MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ???????// 上传的文件 ???????builder.addBinaryBody(fileParamName, file); ???????HttpEntity httpEntity = builder.build(); ???????httpPost.setEntity(httpEntity); ???????// 请求获取数据的超时时间 、 设置从connect ???????// Manager获取Connection超时时间(因为目前版本是可以共享连接池的)、设置连接超时时间 ???????RequestConfig requestConfig = RequestConfig.custom() ???????????????.setSocketTimeout(10000).setConnectionRequestTimeout(3000) ???????????????.setConnectTimeout(10000).build(); ???????httpPost.setConfig(requestConfig); ???????HttpClient httpClient = HttpClients.createDefault(); ???????HttpResponse response = httpClient.execute(httpPost); ???????return EntityUtils.toString(response.getEntity()); ???}}

HttpClient(五)-- 模拟表单上传文件

原文地址:http://www.cnblogs.com/xbq8080/p/7536364.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved