文章目录
- 一、项目、作者何许人也
- 二、观摩庐山真面目
- 三、怎么玩
- 四、后端怎么调用
- 1. RestTemplate测试代码
- 2. 运行结果
一、项目、作者何许人也
httpbin是大神kennethreitz为搭建测试用的http服务而写的项目,httpbin 这个服务应用能测试HTTP请求及响应的各种信息,比如 cookie、ip、headers 和登录验证等,且支持 GET、POST 等多种方法,对 web 开发和测试具有很大的帮助,它是用 Python + Flask 编写的,是一个开源项目。
Kenneth Reitz: 著名的python首席架构师,requests、python-guide、pipenv、legit、autoenv等一系列大名鼎鼎的python类库及工具的创作者,大神级程序员,据说其身价高达5亿美元。
二、观摩庐山真面目
官网 https://httpbin.org/
http方法组展开的接口
其他的分组
点击 HTML form 是一个form表单提交页面,可以用来测试
三、怎么玩
以get请求为例:
展开 HTTP Methods 方法下面的get请求,选择Try it out,
出现 Execute 点击他, Response body 返回json数据。
依次类推,post请求返回数据如下:
包含form表单、json数据、header、url、origin 等信息。
四、后端怎么调用
1. RestTemplate测试代码
这里选取了四个典型场景: get请求、formdata表单提交、json字符串post提交、带文件 multipart/form-data 提交
import java.util.Arrays;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RestTemplateSimpleTest
{
private static RestTemplate restTemplate;
static
{
int type = RandomUtils.nextInt(1, 5);
log.info("--------- type:{}", type);
switch (type)
{
case 1:
// 使用默认客户端构造RestTemplate,写法1
/*** Java HttpURLConnection (默认RestTemplate采用,不支持HTTP2) ***/
restTemplate = new RestTemplate();
break;
case 2:
// 使用默认客户端构造RestTemplate,写法2
restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
break;
case 3:
// 使用默认客户端构造RestTemplate,写法3
restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
break;
case 4:
// 使用默认客户端构造RestTemplate, 配置proxy,connectTimeout,readTimeout等参数
SimpleClientHttpRequestFactory clientHttpRquestFactory = new SimpleClientHttpRequestFactory();
clientHttpRquestFactory.setConnectTimeout(5000);
clientHttpRquestFactory.setReadTimeout(65000);
restTemplate = new RestTemplate(clientHttpRquestFactory);
break;
default:
}
}
@Test
public void testGet()
{
String url = "https://httpbin.org/get";
String responseBody = restTemplate.getForObject(url, String.class);
log.info("responseBody={}", responseBody);
}
@Test
public void testFormData001()
{
// POST请求只能用MultiValueMap
String url = "https://httpbin.org/post";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("q1", "java");
params.add("q2", "python");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
if (RandomUtils.nextBoolean())
{
String response = restTemplate.postForObject(url, requestEntity, String.class);
log.info("ResponseBody={}", response);
}
else
{
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
log.info("ResponseEntity={}", responseEntity.getBody());
}
}
@Test
public void testUpload()
{
// POST请求只能用MultiValueMap
String url = "https://httpbin.org/post";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
// Resource适用于文件、Jar內
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
Resource file = new ClassPathResource("123.jpg");
// 多次调用,后台接受到的是MultipartFile[]
params.add("file", file);
params.add("file", file);
params.add("name", "girl");
params.add("age", "18");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
log.info("ResponseEntity={}", responseEntity);
}
}
2. 运行结果
2024-01-26 17:52:44.587 [main] INFO com.fly.rest.RestTemplateSimpleTest - --------- type:3
2024-01-26 17:52:46.461 [main] INFO com.fly.rest.RestTemplateSimpleTest - responseBody={
"args": {},
"headers": {
"Accept": "text/plain, application/json, application/*+json, */*",
"Host": "httpbin.org",
"User-Agent": "Java/1.8.0_221",
"X-Amzn-Trace-Id": "Root=1-65b379f1-30d6643c75aaf2992a9faa97"
},
"origin": "61.169.67.18",
"url": "https://httpbin.org/get"
}
2024-01-26 17:52:46.710 [main] INFO com.fly.rest.RestTemplateSimpleTest - ResponseEntity=<200,{
"args": {},
"data": "{\"pageNo\":\"2\",\"pageSize\":\"10\",\"keyword\":\"1\"}",
"files": {},
"form": {},
"headers": {
"Accept": "application/json",
"Content-Length": "44",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "Java/1.8.0_221",
"X-Amzn-Trace-Id": "Root=1-65b379f1-4c7461bf00bf0966330cdc84"
},
"json": {
"keyword": "1",
"pageNo": "2",
"pageSize": "10"
},
"origin": "61.169.67.18",
"url": "https://httpbin.org/post"
}
,[Date:"Fri, 26 Jan 2024 09:22:57 GMT", Content-Type:"application/json", Content-Length:"523", Connection:"keep-alive", Server:"gunicorn/19.9.0", Access-Control-Allow-Origin:"*", Access-Control-Allow-Credentials:"true"]>
2024-01-26 17:52:46.942 [main] INFO com.fly.rest.RestTemplateSimpleTest - ResponseBody={
"args": {},
"data": "",
"files": {},
"form": {
"q1": "java",
"q2": "python"
},
"headers": {
"Accept": "application/json",
"Content-Length": "17",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"Host": "httpbin.org",
"User-Agent": "Java/1.8.0_221",
"X-Amzn-Trace-Id": "Root=1-65b379f1-3400da2d5aa686e725741d55"
},
"json": null,
"origin": "61.169.67.18",
"url": "https://httpbin.org/post"
}
2024-01-26 17:52:48.339 [main] INFO com.fly.rest.RestTemplateSimpleTest - ResponseEntity=<200,{
"args": {},
"data": "",
"files": {
"file": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eH3cxK4vJ4Yfpb2ibjlbD9BnG7SEaN8myH5Lt+18DSH1UQCPvpKhrK1j+ij52ppGX42r4TcRZ62Y76GqwOgMEr2HJ4fqbeJuvKyH6H24nabMmOPrGKR61y5p5OH4xnqJRIO/gR4xylWq1GF/ecRvudYcjvnmY8ry3rC9V3gm4vvxhyigmcLVvfwZqlc9uWgBp28Y8tZM1Xtxmo3XY48nAPqYloP34ylNCSccYhuzRhAMoK46AFBHsb/3vCTygDcYJ+M0Mh3NyS/nNQVx7NF38P3jDp86NOGTC3h/l7w7VaRhmkUx2KLuR89PkwGUN6RPg1jlhthYDov5PsxJBI0eyHH3jMao6aHy+XjEUx0eE8aenxh8jnNW+H58znARGaQvwuEjRaDf3P9x7ECqgP++cKg02tscF1jfR95BEBBCb9awVq9Rpf3jLQ6RB+TgxtoEJeF/o/eeOri2nhXk+cQdMNIPyePrJ8qqKz0e8bB8Ckd9uvrIAdcj3+sdqTZG/eJFS7VowQiB0Cz7wBIHEQcTwHkH1gKSAzArb8uCikgkPOczoS3jZr94gAKmDzJQ/WAQAsXYO0ccREWfccFc7VBujd/owCaCBzTY/SZYFFWU4R/wDMRBVBid1XZ+cvGm6HGxx8LhsRNIclpX7fjGAxriPjLmioVKfL+sBFSVwpEf3cugXpD+E4z//Z"
},
"form": {
"age": "18",
"name": "girl"
},
"headers": {
"Accept": "application/json",
"Content-Length": "67257",
"Content-Type": "multipart/form-data;charset=UTF-8;boundary=j8heXoBDLEg1JRe3apeLMkvEeVnkcGIiymWf75",
"Host": "httpbin.org",
"User-Agent": "Java/1.8.0_221",
"X-Amzn-Trace-Id": "Root=1-65b379f1-136ad5f76c66cd7e626c56c5"
},
"json": null,
"origin": "61.169.67.18",
"url": "https://httpbin.org/post"
}
,[Date:"Fri, 26 Jan 2024 09:22:58 GMT", Content-Type:"application/json", Content-Length:"44945", Connection:"keep-alive", Server:"gunicorn/19.9.0", Access-Control-Allow-Origin:"*", Access-Control-Allow-Credentials:"true"]>
未完待续,有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!
-over-