优秀的编程知识分享平台

网站首页 > 技术文章 正文

HttpClient发送InputStream对象(esp32 httpclient reuse connect)

nanyue 2024-08-03 18:12:03 技术文章 6 ℃
  1. public void inputStreamUpload() {
  2. //创建HttpClient对象
  3. CloseableHttpClient client = HttpClients.createDefault();
  4. //构建POST请求 请求地址请更换为自己的。
  5. //1)
  6. HttpPost post = new HttpPost("http://localhost:8003/uploadAndDownload/uploadFileAction");
  7. InputStream inputStream = null;
  8. try {
  9. //文件路径请换成自己的
  10. //2)
  11. inputStream = new FileInputStream("G:\\LearnVideo\\text01.txt");
  12. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  13. builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  14. //第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
  15. //第三个参数是文件名
  16. //3)
  17. builder.addBinaryBody("uploadFile", inputStream, ContentType.create("multipart/form-data"), "text01.txt");
  18. //4)构建请求参数 普通表单项
  19. StringBody stringBody = new StringBody("12",ContentType.MULTIPART_FORM_DATA);
  20. builder.addPart("id",stringBody);
  21. HttpEntity entity = builder.build();
  22. post.setEntity(entity);
  23. //发送请求
  24. HttpResponse response = client.execute(post);
  25. entity = response.getEntity();
  26. if (entity != null) {
  27. inputStream = entity.getContent();
  28. //转换为字节输入流
  29. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
  30. String body = null;
  31. while ((body = br.readLine()) != null) {
  32. System.out.println(body);
  33. }
  34. }
  35. } catch (FileNotFoundException e) {
  36. e.printStackTrace();
  37. } catch (ClientProtocolException e) {
  38. e.printStackTrace();
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. }finally {
  42. if(inputStream != null){
  43. try {
  44. inputStream.close();
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. }
  50. }
最近发表
标签列表