httpcomponents.httpclient 使用
1.使用场景
两个Spring Boot 项目DemoA 和 DemoB。DemoA 需要调用DemoB提供的接口,并且传递数据,接收dmeoB的返回数据。
在使用http请求时,需要考虑
- http请求的是否正常完成, status 200.
- http请求 在服务提供方(Demo B)的response有哪几种情况, 在服务消费方(Demo A)怎么处理这几种response
2. Demo B
1.添加依赖
<properties> <alibaba.fastjson.version>1.2.75</alibaba.fastjson.version> <projecglombok.version>1.18.18</projecglombok.version> </properties> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${alibaba.fastjson.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${projecglombok.version}</version> </dependency>
3. request 请求实体类
import lombok.Data; @Data public class StudentRequest { private String name; private Integer age; private String attachmentFolder; private String attachmentName; private byte[] attachment; }
4. response 响应实体类
import lombok.Data; @Data public class StudentResponse { private String result; private String message; }
5. 文件工具类 Java 文件和字节数组互转
6. controller 服务提供
import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; @RestController @RequestMapping("/api/student") public class StudentController { Logger logger = LoggerFactory.getLogger(StudentController.class); @PostMapping("/search") public StudentResponse search(@RequestBody StudentRequest request) throws InterruptedException { logger.info("request is {}", JSONObject.toJSONString(request)); StudentResponse studentResponse = new StudentResponse(); studentResponse.setResult("success"); studentResponse.setMessage("wow! success! "); logger.info("request return {}", JSONObject.toJSONString(studentResponse)); return studentResponse; } @PostMapping(value = "/save") public ResponseEntity<StudentResponse> save(@RequestBody StudentRequest studentRequest) { StudentResponse studentResponse = new StudentResponse(); logger.info("student name is {},age is {}", studentRequest.getName(), studentRequest.getAge()); String filePath = studentRequest.getAttachmentFolder(); String fileName = studentRequest.getAttachmentName(); byte[] fileContent = studentRequest.getAttachment(); FileUtil.byte2File(fileContent, filePath, fileName); studentResponse.setResult("success"); studentResponse.setMessage("wow! success! "); return new ResponseEntity<>(studentResponse, HttpStatus.OK); } @PostMapping(value = "/saveList") public ResponseEntity<StudentResponse> save(@RequestBody List<StudentRequest> studentRequests) { StudentResponse studentResponse = new StudentResponse(); for (StudentRequest studentRequest : studentRequests) { logger.info("student name is {},age is {}", studentRequest.getName(), studentRequest.getAge()); String filePath = studentRequest.getAttachmentFolder(); String fileName = studentRequest.getAttachmentName(); byte[] fileContent = studentRequest.getAttachment(); FileUtil.byte2File(fileContent, filePath, fileName); } studentResponse.setResult("success"); studentResponse.setMessage("wow! success! "); return new ResponseEntity<>(studentResponse, HttpStatus.OK); } }
1. 添加依赖
<properties> <alibaba.fastjson.version>1.2.75</alibaba.fastjson.version> <projecglombok.version>1.18.18</projecglombok.version> <httpclient.version>4.5.13</httpclient.version> </properties> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${alibaba.fastjson.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${projecglombok.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency>
2. 配置文件 application.properties
file.folder=C:/test/demoB/ #url url.http = http://localhost:8010/api url.student.search = /student/search url.student.save = /student/save url.student.saveList =/student/saveList
4. FileUtil 工具类 Java 文件和字节数组互转
5. HttpClient 工具类 和 HttpResponseEntity
import lombok.Data; @Data public class HttpResponseEntity { private Integer statusCode; private String responseMessage; }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HttpClientUtil { static Logger logger = LoggerFactory.getLogger(DemoAApplication.class); public static HttpResponseEntity doPost(String url, String data) { HttpResponseEntity httpResponseEntity = new HttpResponseEntity(); // 1.创建HttpGet实例 HttpPost post = new HttpPost(url); // 2.设置请求体 StringEntity myEntity = new StringEntity(data, ContentType.APPLICATION_JSON); post.setEntity(myEntity); // 3.使用HttpClient发送get请求,获得返回结果HttpResponse CloseableHttpClient client = HttpClients.createDefault(); try { // 4.从connect Manager获取Connection 超时时间3min, 连接目标超时 5min, 等待响应超时10min RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(180000).setConnectTimeout(300000).setSocketTimeout(600000).build(); post.setConfig(requestConfig); // 5.读取返回结果 HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); httpResponseEntity.setStatusCode(statusCode); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String resultMessage = reader.readLine(); reader.close(); in.close(); httpResponseEntity.setResponseMessage(resultMessage); } } catch (Exception e) { httpResponseEntity.setStatusCode(0); logger.error("HTTP POST Error, url is {}", url); logger.error(e.getMessage(), e); } finally { if (null != client) { try { client.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } return httpResponseEntity; } }
import java.io.File; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; @RestController @RequestMapping("/api/student") public class StudentController { @Value("${file.folder}") private String fileFolder; @Value("${url.http}") private String urlHttp; @Value("${url.student.search}") private String urlStudentSearch; @Value("${url.student.save}") private String urlStudentSave; @Value("${url.student.saveList}") private String urlStudentSaveList; Logger logger = LoggerFactory.getLogger(StudentController.class); @GetMapping("/search") public void search() { // 请求参数 StudentRequest request = new StudentRequest(); request.setName("xiaoming"); request.setAge(22); String requestString = JSONObject.toJSONString(request); // 请求url String serviceUrl = urlHttp + urlStudentSearch; // 执行请求 HttpResponseEntity httpResponseEntity = HttpClientUtil.doPost(serviceUrl, requestString); // 请求返回 if (httpResponseEntity.getStatusCode() == 200) { StudentResponse studentResponse = JSONObject.parseObject(httpResponseEntity.getResponseMessage(), StudentResponse.class); logger.info("studentResponse is {}", JSONObject.toJSONString(studentResponse)); } } @GetMapping("/save") public void save() { // 请求参数 StudentRequest request = new StudentRequest(); request.setName("xiaoming"); request.setAge(22); request.setAttachmentName("test.xls"); request.setAttachmentFolder(fileFolder); byte[] fileByte = FileUtil.file2Byte(new File("C:\\test\\demoA\\test.xls")); request.setAttachment(fileByte); String requestString = JSONObject.toJSONString(request); // 请求url String serviceUrl = urlHttp + urlStudentSave; // 执行请求 HttpResponseEntity httpResponseEntity = HttpClientUtil.doPost(serviceUrl, requestString); // 请求返回 if (httpResponseEntity.getStatusCode() == 200) { StudentResponse studentResponse = JSONObject.parseObject(httpResponseEntity.getResponseMessage(), StudentResponse.class); logger.info("studentResponse is {}", JSONObject.toJSONString(studentResponse)); } } @GetMapping("/saveList") public void saveList() { // 请求参数 List<StudentRequest> studentRequests = new ArrayList<StudentRequest>(); StudentRequest studentRequest1 = new StudentRequest(); studentRequest1.setName("Melody"); studentRequest1.setAge(22); studentRequest1.setAttachmentName("test1.xls"); studentRequest1.setAttachmentFolder(fileFolder); byte[] fileByte = FileUtil.file2Byte(new File("C:\\test\\demoA\\test1.xls")); studentRequest1.setAttachment(fileByte); studentRequests.add(studentRequest1); StudentRequest studentRequest2 = new StudentRequest(); studentRequest2.setName("Sara"); studentRequest2.setAge(21); studentRequest2.setAttachmentName("test2.xls"); studentRequest2.setAttachmentFolder(fileFolder); byte[] fileByte2 = FileUtil.file2Byte(new File("C:\\test\\demoA\\test2.xls")); studentRequest2.setAttachment(fileByte2); studentRequests.add(studentRequest2); String requestString = JSONObject.toJSONString(studentRequests); // 请求url String serviceUrl = urlHttp + urlStudentSaveList; // 执行请求 HttpResponseEntity httpResponseEntity = HttpClientUtil.doPost(serviceUrl, requestString); // 请求返回 if (httpResponseEntity.getStatusCode() == 200) { StudentResponse studentResponse = JSONObject.parseObject(httpResponseEntity.getResponseMessage(), StudentResponse.class); logger.info("studentResponse is {}", JSONObject.toJSONString(studentResponse)); } } }
测试: 启动两个项目
http://localhost:8080/api/student/search
http://localhost:8080/api/student/save
http://localhost:8080/api/student/saveList
分别执行Demo A 的三个方法, 前提保证待传输的文件存在