OkHttp接口自动化测试

发布于:2025-02-10 ⋅ 阅读:(43) ⋅ 点赞:(0)

java环境搭建

  • 引入依赖
<!--okhttp3-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

OkHttp之get

  • 基本语法格式
	// 1.创建一个OkHttpClient
    OkHttpClient okHttpClient = new OkHttpClient();
    // 2.创建一个Request  (对应的数据:url、请求数据)
    Request request = new Request.Builder()
            .url("https://www.baidu.com")
            .build();
    // 3.发送请求
    Response response = okHttpClient.newCall(request).execute();
    // 4.获取响应
    String result = response.body().string();    
    // 5.关闭连接
    response.close();

在这里插入图片描述

OkHttp之POST

POST发送From表单

  • post请求
package interfaceTest;

import okhttp3.*;

import java.io.IOException;

public class PostDemo {
    public static void main(String[] args) throws IOException {
        // 1.创建一个OkHttpClient  (发送请求)
        OkHttpClient okHttpClient = new OkHttpClient();
        // 2.创建一个Request  (对应的数据:url、请求数据)

        // 构造请求参数
        RequestBody requestBody = new FormBody.Builder()
                .add("username", "zhangsan")  // 用户名
                .add("password", "123456") // 密码
                .build();

        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/login")
                .post(requestBody)
                .build();
        // 3.发送请求
        Response response = okHttpClient.newCall(request).execute();

        // 4.获取响应
        String result = response.body().string();

        if(response.isSuccessful()) {
            System.out.println("请求成功");
            System.out.println(result);
        }

        // 5.关闭连接
        response.close();
    }
}

在这里插入图片描述
在body中,需要主要数据格式
以下是一个常见的Content-Type(内容类型)与请求体(body)对应关系示例图表,主要涵盖了几种常见的在网络请求等场景中会用到的类型:

Content-Type 描述 示例 Body 格式
application/json 用于表示数据以 JSON 格式传输,常用于 RESTful API 交互等场景。 {"name": "John", "age": 30, "city": "New York"}(JSON 对象形式,包含键值对)
application/x-www-form-urlencoded 数据被编码成键值对形式,类似 URL 查询字符串的格式,常用于 HTML 表单提交(传统方式)。 name=John&age=30&city=New York(键值对用 & 连接,键和值之间用 = 连接)
multipart/form-data 常用于在一个请求中同时上传文件和包含其他表单数据,它把不同类型的数据分成多个部分来传输。 以下是一个简单示例,包含文本和文件两部分:
--boundary_string
Content-Disposition: form-data; name=“text_data”

Some text here
–boundary_string
Content-Disposition: form-data; name=“file”; filename=“example.txt”
Content-Type: text/plain

[文件内容,此处省略具体文本展示]
–boundary_string-- (其中 boundary_string 是用于分隔各部分的边界字符串,会自动生成)
text/plain 表示纯文本格式,常用于简单的文本数据传输。 This is a simple text message(就是普通的文本内容)

你可以根据实际使用场景进行参考,不同的应用场景和开发框架中,具体的使用细节和规则可能会有一定差异。

在这里插入图片描述

POST发送json

  • POST发送json格式
package interfaceTest;

import okhttp3.*;

import java.io.IOException;

// 通过post发送json格式的数据    
public class PostAddChartDemo {
    public static void main(String[] args) throws IOException {
        // 1.创建一个OkHttpClient  (发送请求)
        OkHttpClient okHttpClient = new OkHttpClient();
        // 2.创建一个Request  (对应的数据:url、请求数据)

        // 创建一个请求体 -body
       String data = "{\"username\":\"admin\",\"password\":\"123456\"}";

//       RequestBody requestBody = RequestBody.create(数据格式,数据);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);


        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/login/addChartButByMoke")
                .post(requestBody)
                .build();
        // 3.发送请求
        Response response = okHttpClient.newCall(request).execute();

        // 4.获取响应
        String result = response.body().string();

        if(response.isSuccessful()) {
            System.out.println("请求成功");
            System.out.println(result);
        }

        // 5.关闭连接
        response.close();
    }
}

POST上传文件

 public static void main(String[] args) throws IOException {
        // 1.创建一个OkHttpClient  (发送请求)
        OkHttpClient okHttpClient = new OkHttpClient();

        // 数据格式
        MediaType mediaType =  MediaType.parse("image/jpeg");

        // 构造请求参数 - 文件
        File filePath = new File("C:\\youFilePath");
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart
                        ("file", "youFileName", RequestBody.create(mediaType, filePath))
                .build();
        
        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/postFile")
                .post(requestBody)
                .build();
        // 3.发送请求
        Response response = okHttpClient.newCall(request).execute();

        // 4.获取响应
        String result = response.body().string();

        if(response.isSuccessful()) {
            System.out.println("请求成功");
            System.out.println(result);
        }

        // 5.关闭连接
        response.close();
    }

OkHttp之delete

 public static void main(String[] args) throws IOException {
        // 1.创建一个OkHttpClient  (发送请求)
        OkHttpClient okHttpClient = new OkHttpClient();

        // 数据 171 可以分离出来
        String userId = new String("171");
        String url = String.format("http://127.0.0.1:8080/login/deleteChartButByMoke/%s", userId);
        // 然后把url放到url里面

        // 2.创建一个Request  (对应的数据:url、请求数据)
        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/login/deleteChartButByMoke/171")
                .delete()
                .build();
        // 3.发送请求
        Response response = okHttpClient.newCall(request).execute();

        // 4.获取响应
        String result = response.body().string();
        if(response.isSuccessful()) {
            System.out.println("请求成功");
            System.out.println(result);
        }

        // 5.关闭连接
        response.close();
    }

OkHttp之put

public static void main(String[] args) throws IOException {
        // 1.创建一个OkHttpClient  (发送请求)
        OkHttpClient okHttpClient = new OkHttpClient();

        // 数据 171 可以分离出来
        String userId = new String("171");
        String url = String.format("http://127.0.0.1:8080/login/deleteChartButByMoke/%s", userId);
        // 然后把url放到url里面

        // 构建需要修改的数据

        RequestBody requestBody = new FormBody.Builder()
                .add("userId", userId)
                .add("userName", "zhangsan")
                .add("password", "123456")
                .add("email", "123456@qq.com")
                .add("phone", "123456")
                .add("sex", "男")
                .add("birthday", "1999-01-01")
                .build();


        // 2.创建一个Request  (对应的数据:url、请求数据)
        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/login/deleteChartButByMoke/171")
                .put(requestBody)
                .build();
        // 3.发送请求
        Response response = okHttpClient.newCall(request).execute();

        // 4.获取响应
        String result = response.body().string();
        if(response.isSuccessful()) {
            System.out.println("请求成功");
            System.out.println(result);
        }

        // 5.关闭连接
        response.close();
    }

网站公告

今日签到

点亮在社区的每一天
去签到