分享web开发知识

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

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

通过HttpClient4.5模拟Form表单文件上传

发布时间:2023-09-06 01:47责任编辑:苏小强关键词:文件上传
public static void main(String[] args) { ???????CloseableHttpClient httpclient = HttpClients.createDefault(); ???????CloseableHttpResponse response = null; ???????String result = null; ???????InputStream inputStream = null; ???????try { ???????????inputStream = new FileInputStream("D:\\test.pdf"); ???????????HttpPost httpPost = new HttpPost("http://127.0.0.1/test"); ???????????MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ???????????builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ???????????builder.addBinaryBody("wj", inputStream, ContentType.create("multipart/form-data"), "test.pdf"); ???????????????????????//构建请求参数 普通表单项 ?????????????StringBody stringBody = new StringBody("100001", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("serial_no", stringBody); ???????????stringBody = new StringBody("200", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("xPosition", stringBody); ???????????stringBody = new StringBody("200", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("yPosition", stringBody); ???????????stringBody = new StringBody("2", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("sealType", stringBody); ???????????stringBody = new StringBody("1", ContentType.MULTIPART_FORM_DATA); ???????????builder.addPart("paegNum", stringBody); ???????????????????????builder.setCharset(CharsetUtils.get("UTF-8")); ???????????HttpEntity entity = builder.build(); ???????????httpPost.setEntity(entity); ???????????response = httpclient.execute(httpPost); ???????????int statusCode = response.getStatusLine().getStatusCode(); ???????????System.out.println("statusCode:" + statusCode); ???????????if (statusCode == HttpStatus.SC_OK) { ???????????????HttpEntity resEntity = response.getEntity(); ???????????????result = EntityUtils.toString(resEntity, "UTF-8"); ???????????} ???????????System.out.println("result:" + result); ???????} catch (IOException ex) { ???????????Logger.getLogger(QzTest.class.getName()).log(Level.SEVERE, null, ex); ???????} finally { ???????????try { ???????????????if (null != inputStream) { ???????????????????inputStream.close(); ???????????????} ???????????} catch (IOException ex) { ???????????????Logger.getLogger(QzTest.class.getName()).log(Level.SEVERE, null, ex); ???????????} finally { ???????????????httpclient.getConnectionManager().shutdown(); ???????????} ???????} ???}

依赖包:

commons-logging-1.2.jar

httpclient-4.5.3.jar

httpcore-4.4.6.jar

httpmime-4.5.3.jar

通过HttpClient4.5模拟Form表单文件上传

原文地址:https://www.cnblogs.com/yshyee/p/8681507.html

知识推荐

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