一个服务访问另外一个服务的技术有很多种,比如feign, dubbo, activemq, ajax+jsonp等,okhttp3是其中之一。本文将阐述如何通过okhttp3去访问另外一个服务的api。
1、前提约束
- 创建springboot项目,提供待访问的api
https://www.jianshu.com/p/de979f53ad80 - 再次创建springboot项目
https://www.jianshu.com/p/1ad292812ab1 - 在第二个项目中加入以下依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>
- 在主启动类同级目录下加入Okhttp3Controller.java
@RestController
public class Okhttp3Controller{
@GetMapping("/gettest")
public String gettest()throws Exception
{
String url = "http://localhost:8080/get/"+pageid;
OkHttpClient okHttpClient = new OkHttpClient();
MediaType json = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
String result = response.body().string();
System.out.println(result);
jsonObject.put("previewurl",result);
return jsonObject;
}
@GetMapping("/post")
public String posttest()throws Exception{
Student student = new Student();
student.setId(123);
student.setName("ali");
ObjectMapper objectMapper = new ObjectMapper();
String Json=objectMapper.writeValueAsString(student); //转JSON
String url = "http://localhost:8080/posttest";
OkHttpClient okHttpClient = new OkHttpClient();
MediaType json = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(json,Json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
String result = response.body().string();
System.out.println(result);
return "ok";
}
}
class Student{
private int id;
private String name;
...//完成构造方法和get、set方法
}
至此,我们完成了通过okhttp3去访问另外一个服务中get和post的api之测试。
网友评论