一、如何mock一个接口
postman操作
看见这个界面就是简单的配置完成啦~
在这里可以调用我们之前配置的mock服务,点击send后能看到我们配置的response body
代码调用接口
我这里是使用的SpringCloud的@FeignClient
调用
@FeignClient(url = "https://ea6d6f75-9537-4701-ad88-54d1de82f4ba.mock.pstmn.io", name = "demo")
public interface DemoClient {
@GetMapping("/my/path1")
Map<String, Object> func();
}
但是!执行报错:
feign.codec.DecodeException: Could not extract response: no suitable HttpMessageConverter found for response type [***] and content type [text/html;charset=utf-8]
Caused by: org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [***] and content type [text/html;charset=utf-8]
大概翻译翻译就是之前mock的服务默认的content type是[text/html;charset=utf-8]。也就是被当成是html的字符串了,只能返回String。而我在这里想用的map来接收,或者用一个pojo类来接收,都无法从字符串转换过来,而是需要一个json。
那么怎么让mock服务返回一个json对象呢?postman在Collections页签下提供了方法。详情入下:
二、如何详细设置mock的请求与返回
在这个界面可以修改之前配置的mock服务的request和response。
之前在mock service界面只是简单的配置了respons的body。在这个界面不仅可以修改之前配置的body,还能修改request和response的header。
在response的header里,增加一项配置Content-Type
: application/json
,保存一下。
再重新在代码内调用一下,已经能正常接收到了