31 使用okhttp3访问另外一个项目

2020-07-28  本文已影响0人  张力的程序园

一个服务访问另外一个服务的技术有很多种,比如feign, dubbo, activemq, ajax+jsonp等,okhttp3是其中之一。本文将阐述如何通过okhttp3去访问另外一个服务的api。

1、前提约束

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.1</version>
        </dependency>
@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之测试。

上一篇下一篇

猜你喜欢

热点阅读