Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件。关于PostMan的下载和使用网上有很多相关的博客介绍,本文主要介绍PostMan在进行模拟Http请求后可以根据需要的开发语言,快速生成相应代码的过程。
示例请求以Microsoft Azure认知服务人脸识别Detect方法为例。
PostMan示例截图:
Body内容:
{
"url": "http://www.gjstars.com/img/2017-4-17-67.jpg"
}
PostMan生成代码:
使用PostMan自带Code功能生成JAva 代码:
Java中使用OkHttpClient使用生成的代码测试。
Maven依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
Java 测试:
Java Code:
import okhttp3.*;
import java.io.IOException;
public class PostManDemo {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n \"url\": \"http://www.gjstars.com/img/2017-4-17-67.jpg\"\r\n}");
Request request = new Request.Builder()
.url("https://api.cognitive.azure.cn/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Ocp-Apim-Subscription-Key", "73db498eb79943768d2a012a39b03e5f")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "715400ac-fb98-b4ae-9c55-c7cf105e44be")
.build();
Response response = client.newCall(request).execute();
//打印输出结果
System.out.println(response.body().string());
}
}
结果:
[{"faceId":"16760c9f-13f2-4318-89a1-f0884220b64c","faceRectangle":{"top":85,"left":68,"width":146,"height":146},"faceAttributes":{"age":25.8}}]