OkHttpClient如何发get请求以及post请求

这篇具有很好参考价值的文章主要介绍了OkHttpClient如何发get请求以及post请求。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一:get请求

  1. 加入依赖
<dependency>
              <groupId>com.squareup.okhttp3</groupId>
              <artifactId>okhttp</artifactId>
              <version>3.4.1</version>
        </dependency>

  1. 写代码
    2.1配置OkHttpClient
    2.2请求参数
    2.3请求头配置
public class Test{
private static OkHttpClient httpClient;
    static {
        httpClient = new OkHttpClient.Builder()
                //设置连接超时时间
                .connectTimeout(30, TimeUnit.SECONDS)
                //设置读取超时时间
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }
   
   //该接口假设为被对接的接口
@GetMapping("/getApplicationConfig")
    public ApplicationConfigVO getApplicationConfig(@RequestParam("type") int type){
        ApplicationConfigVO configVO = new ApplicationConfigVO();
        //pc端是type是1,移动端type2
        if (type==1){
            configVO.setApplicationId(pcApplicationId);
        }else {
            configVO.setBusinessModelId(businessModelId);
            
        }
       return configVO;
    }
     
     //这是测试接口
    @GetMapping("/test")
    public ApplicationConfigVO test(@RequestParam("type") int type, HttpServletRequest request1){
        Response response = null;
        ApplicationConfigVO configVO;
        try {
            Request request = new Request.Builder()
                     //这里必须手动设置为json内容类型
                    .addHeader("content-type", "application/json")
                    //设置token
                    .addHeader("x-auth0-token",request1.getHeader("x-auth0-token"))
                    //参数放到链接后面
                    .url("http://localhost:18008/application/getApplicationConfig?type="+type)             
                    .build();
                    //发送请求
            response = httpClient.newCall(request).execute();
            //将响应数据转换字符传(实际是json字符传)
            String respStr = response.body().string();
            //将响应数据转换json对象
            JSONObject object = JSONObject.parseObject(respStr);
            //取json对象指定数据
            JSONObject jsonObject = object.getJSONObject("data");
            //将数据转换指定的对象
             configVO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), ApplicationConfigVO.class);
        } catch (Exception e) {
            log.error("获取配置失败:{}", e.getMessage(), e);
            throw new RestException("获取配置失败:" + e.getMessage());
        } finally {
            if (null != response) {
                response.close();
            }
        }
        return configVO;
    }
}

二:post请求

  1. 加入依赖
<dependency>
              <groupId>com.squareup.okhttp3</groupId>
              <artifactId>okhttp</artifactId>
              <version>3.4.1</version>
        </dependency>

  1. 写代码
    2.1配置OkHttpClient
    2.2请求参数
    2.3请求头配置
public class Test{
private static OkHttpClient httpClient;
    static {
        httpClient = new OkHttpClient.Builder()
                //设置连接超时时间
                .connectTimeout(30, TimeUnit.SECONDS)
                //设置读取超时时间
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }
   
   //该接口假设为被对接的接口
@PostMapping("/getApplicationConfig")
    public ApplicationConfigVO getApplicationConfig(@RequestBody SubcategoryVO subcategoryVO, HttpServletRequest request1){
       String status = subcategoryVO.getStatus();
        int type = Integer.parseInt(status);
        ApplicationConfigVO configVO = new ApplicationConfigVO();
        //pc端是type是1,移动端type2
        if (type==1){
            configVO.setApplicationId(pcApplicationId);
        }else {
            configVO.setBusinessModelId(businessModelId);
            
        }
       return configVO;
    }

    @GetMapping("/test")
    public ApplicationConfigVO test(@RequestParam("type") int type, HttpServletRequest request1){
        Response response = null;
        ApplicationConfigVO configVO;
        try {
            //设置请求参数
            JSONObject paramObject = new JSONObject();
            paramObject.put("status", type);
            Request request = new Request.Builder()
                     //这里必须手动设置为json内容类型
                    .addHeader("content-type", "application/json")
                    //设置token
                    .addHeader("x-auth0-token",request1.getHeader("x-auth0-token"))
                    //参数放到链接后面
                    .url("http://localhost:18008/application/getApplicationConfig)             
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramObject.toString()))
                    .build();
                    //发送请求
            response = httpClient.newCall(request).execute();
            //将响应数据转换字符传(实际是json字符传)
            String respStr = response.body().string();
            //将响应数据转换json对象
            JSONObject object = JSONObject.parseObject(respStr);
            //取json对象指定数据
            JSONObject jsonObject = object.getJSONObject("data");
            //将数据转换指定的对象
             configVO = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), ApplicationConfigVO.class);
        } catch (Exception e) {
            log.error("获取配置失败:{}", e.getMessage(), e);
            throw new RestException("获取配置失败:" + e.getMessage());
        } finally {
            if (null != response) {
                response.close();
            }
        }
        return configVO;
    }
}

文章来源地址https://www.toymoban.com/news/detail-544737.html

到了这里,关于OkHttpClient如何发get请求以及post请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 原生js创建get/post请求以及封装方式、axios的基本使用

    原生js创建get请求 原生js创建post请求 原生get和post封装方式1 原生get和post封装方式2 axios的基本使用

    2024年02月21日
    浏览(31)
  • java调用http接口(get请求和post请求)

    1.http接口的格式如下: 图片选择失败,我只能把数据贴出来,如果有不懂的可以问我哈。 http://localhost:8881/department/getDepartmentList接口数据如下:(请求方式是GET) http://localhost:8881/department/getDataById?id=3接口数据如下:(请求方式是POST) 2.需要引入的包有: 3.实现方法如下:

    2024年02月13日
    浏览(41)
  • java中使用hutool调用get请求,post请求

    一、hutool工具包实现 1、get请求 2、post请求 二、java net实现 1、java中http协议调用get请求 2、java中https协议调用get请求

    2024年02月11日
    浏览(34)
  • Java发送HTTP GET/POST请求

    在这篇文章中,将向你展示四种发送Http的GET/POST的例子,如下: 在Java11的java.net.http.*包中,有一个HttpClient类可以完成HTTP请求。 Java11HttpClientExample.java 本例使用HttpURLConnection(http)和HttpsURLConnection(https) HttpURLConnectionExample.java 使用Apache HttpClient完成HTTP请求的发送需要添加Maven依赖

    2024年02月13日
    浏览(29)
  • Java发起Post 、Get 各种请求整合

    java发起get请求和post请求的各种情况整合。具体看代码以及注释。其中Constants.UTF8本质是指\\\"UTF-8\\\"

    2024年02月04日
    浏览(40)
  • Java http GET POST 请求传参

    HTTP POST请求传参方式 方式一: 方式二 HTTP GET请求传参方式

    2024年02月15日
    浏览(36)
  • java封装https的get、post请求

    话不多说,直接进入正题。 原生的方法,java8中全部都有

    2024年02月11日
    浏览(34)
  • 在 Linux 系统中,如何发起POST/GET请求

    在 Linux 系统中,可以使用命令行工具 `curl` 或者 `wget` 来发送 POST 请求。这两个工具都是非常常用的命令行工具,可以通过命令行直接发送 HTTP 请求。 1. 使用 `curl` 发送 POST 请求: 解释: - `-X POST`: 指定请求的方法为 POST。 - `-H \\\"Content-Type: application/json\\\"`: 指定请求头中的 Cont

    2024年02月15日
    浏览(31)
  • 如何使用postman 进行get或post请求通俗讲解

    get请求,可以直接用浏览器拼上参数,即可进行访问,也可以通过postman访问; 1、通过浏览器:比如宿主机IP拼上参数,比如:http://10.1.1.67:55000/config   2、通过postman访问,选择get,然后输入http://10.1.1.67:55000/config,点击send   浏览器不可以,只能用postman方式,主要有几点,选

    2024年02月14日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包