马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
转自:
http://www.java265.com/JavaCourse/202204/2938.html
HttpClient是一个java语言编写的包,
我们使用HttpClient可以非常方便的发送Http请求
它使基于Http协议请求内容变得非常简单
HttpClient是Apache Jakarta Common下的子项目 它里面封装了很多使用http协议访问的工具,可用于高效访问http
下文笔者讲述基于HttpClient Utils工具类编写一个文件上传的示例分享,如下所示:- HttpClient Utils进行表单进行文件上传的示例分享,如下所示
- 实现思路:
- 1.获取连接
- 2.声明一个HttpPost
- 3.创建上传体FileBody
- 4.定义一个HttpEntity传送文件
- 5.execute执行上传操作
- 6.获取返回信息
- 7.关闭连接
复制代码- /**
- * 上传文件
- */
- public void upload() {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- HttpPost httppost = new HttpPost("http://java265.com/uploadFile");
-
- FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
- StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
-
- HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
-
- httppost.setEntity(reqEntity);
-
- System.out.println("executing request " + httppost.getRequestLine());
- CloseableHttpResponse response = httpclient.execute(httppost);
- try {
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- HttpEntity resEntity = response.getEntity();
- if (resEntity != null) {
- 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();
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |