美文网首页
31 使用okhttp3访问另外一个项目

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

作者: 张力的程序园 | 来源:发表于2020-07-28 18:09 被阅读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>
    
    • 在主启动类同级目录下加入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之测试。

    相关文章

      网友评论

          本文标题:31 使用okhttp3访问另外一个项目

          本文链接:https://www.haomeiwen.com/subject/nxhqrktx.html