HttpClient Get/Post方式调用第三方接口
package www.maxinhai.com.transfer.controller; import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import www.maxinhai.com.transfer.domain.Note; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.time.LocalDateTime; @RestController @RequestMapping("/transfer") public class TransferController { private final static Logger logger = LoggerFactory.getLogger(TransferController.class); /** * Get请求 */ @RequestMapping(value = "/transferByGet", method = RequestMethod.GET) public void transferByGet() { logger.info("transferByGet method start " + LocalDateTime.now()); Note note = new Note(); note.setNoteId(202003092044l); note.setTitle("创建日记"); note.setContent("hello world"); note.setType("test"); note.setUser("maxinhai"); note.setCreateTime(LocalDateTime.now()); // 构造httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); //url地址 URI uri = null; try { String jsonStr = JSON.toJSONString(note); uri = new URIBuilder("http://127.0.0.1:8529/note/addNote").setParameter("note", jsonStr).build(); } catch (URISyntaxException e) { logger.info("transferByGet method error: " + e.getMessage()); } HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("Content-Type","application/json"); httpGet.setHeader("Accept", "application/json"); CloseableHttpResponse response = null; try { //执行Get请求 response = httpclient.execute(httpGet); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = response.getEntity(); String respContent = EntityUtils.toString(httpEntity, "UTF-8"); System.out.println("respContent: " + respContent); } } catch (IOException e) { logger.info("transferByGet method error: " + e.getMessage()); } finally { try { if(response != null) { response.close(); } httpclient.close(); } catch (IOException e) { logger.info("transferByGet method error: " + e.getMessage()); } logger.info("transferByGet method end " + LocalDateTime.now()); } } /** * Post请求 */ @RequestMapping(value = "/transferByPost", method = RequestMethod.GET) public void transferByPost() { logger.info("transferByPost method start " + LocalDateTime.now()); Note note = new Note(); note.setNoteId(202003091959l); note.setTitle("创建日记"); note.setContent("hello world"); note.setType("test"); note.setUser("maxinhai"); note.setCreateTime(LocalDateTime.now()); // 构造httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://127.0.0.1:8529/note/createNote"); // 在传送复杂嵌套对象时,一定要把对象转成json字符串,我这里实用的是alibaba.fastjson,当然你也可以使用其他的json工具 httpPost.addHeader("Content-Type","application/json"); httpPost.setHeader("Accept", "application/json"); //requestEntity.setContentEncoding("UTF-8"); String jsonStr= JSON.toJSONString(note); StringEntity requestEntity=new StringEntity(jsonStr,"UTF-8"); httpPost.setEntity(requestEntity); CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = response.getEntity(); String respContent = EntityUtils.toString(httpEntity, "UTF-8"); System.out.println("respContent: " + respContent); } } catch (IOException e) { logger.info("transferByPost method error: " + e.getMessage()); } finally { try { if(response != null) { response.close(); } httpclient.close(); } catch (IOException e) { logger.info("transferByPost method error: " + e.getMessage()); } logger.info("transferByPost method end " + LocalDateTime.now()); } } }
上面是HttpClient调用服务代码,端口8520
被调用接口,端口8529:
package www.maxinhai.com.note.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import www.maxinhai.com.note.domain.Note; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping(value = "/note") public class NoteController { private final static Logger logger = LoggerFactory.getLogger(NoteController.class); /** * * @param note * @return * @desc 加上这个注解@RequestParam("note") Required Note parameter 'note' is not present] */ @RequestMapping(value = "/addNote", method = RequestMethod.GET) public Map<String, Object> addNote(@RequestBody Note note) { logger.info("addNote method start " + LocalDateTime.now()); Map<String, Object> result = new HashMap<>(); System.out.println(note.toString()); result.put("code", 200); result.put("message", "getMethod success"); result.put("data", null); logger.info("addNote method end " + LocalDateTime.now()); return result; } /** * * @param note * @return * @desc 加上这个注解@RequestParam("note") Required Note parameter 'note' is not present] */ @RequestMapping(value = "/createNote", method = RequestMethod.POST) public Map<String, Object> createNote(@RequestBody Note note) { logger.info("createNote method start " + LocalDateTime.now()); Map<String, Object> result = new HashMap<>(); System.out.println(note.toString()); result.put("code", 200); result.put("message", "postMethod success"); result.put("data", null); logger.info("createNote method end " + LocalDateTime.now()); return result; } }
使用jar包:
<!--HttpClient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.10</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency>