代码实战中okHttp和cookie的使用

在该文中,将大量使用代码举例,包括韩请求参数,get,post请求,请求体,添加cookie,token等的url示例

获取请求体中的多个cookie

Map<String,String> result = new HashMap<>();
List<String> cookies = response.headers("Set-Cookie");
result.put("cookie",String.join(";",cookies));

 Http请求体格式

格式用途
application/x-www-form-urlencoded表单数据提交,键值对形式
multipart/form-data文件上传和复杂表单数据
application/jsonJSON 格式的数据,适合 API 交互
application/xml XML 格式的数据,适合复杂结构化数据
application/octet-stream二进制数据,如文件上传
text/plain纯文本数据
application/x-protobufProtocol Buffers 格式的二进制数据
application/graphqlGraphQL 查询语言
application/x-amfAction Message Format,用于 Flash/Flex 应用程序
application/x-www-form-urlencoded包含数组的表单数据

含有请求参数的GET请求

  • 在该请求中将code封装到请求头中。
  • 在获取响应体后,通过正则表达式获取自己需要的url进行拼接。result.put("url",config.getEndpoint()+matcher.group().replace("amp;",""));对body中可能出现的amp进行清除。
  • 如果url为上一个响应体的响应头获取可以result.put("location",response.header("Location"));来拿到值。
 HttpUrl url = Objects.requireNonNull(HttpUrl.parse(config.getEndpoint() + "/protocol/auth"))
                .newBuilder()
                .addQueryParameter("code","code")
                .build();
        Request request = new Request.Builder()
                .get().url(url).build();
 try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response.body().string());
            }
            assert response.body() != null;
            String regex = "\\/login\\?[^\"']*";
            Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);
            String ss = response.body().string();
            Matcher matcher = pattern.matcher(ss);
while (matcher.find()) {
                result.put("url",config.getEndpoint()+matcher.group().replace("amp;",""));
    }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }

含有Cookie的GET请求

        Request request = new Request.Builder()
                .url(params.get("url"))
                .addHeader("Cookie",params.get("cookie"))
                .get()
                .build();

 含有Token的GET请求

        Request findRequest = new Request.Builder()
                .url(findUrl)
                .addHeader("Authorization", token )
                .get()
                .build();

含有请求体为text/plain的POST请求

        Request comitRequest = new Request.Builder()
                .url(comitUrl)
                .addHeader("Authorization", token )
                .post( RequestBody.create(MediaType.get("text/plain"),stringData))
                .build();

含有请求体为application/x-www-form-urlencoded的POST请求

FormBody formBody = new FormBody.Builder()
                .add("lastName", lastName)
                .add("firstName", firstName)
                .add("gender",gender)
                .add("username",username)
                .add("password",password)
                .build();
        Request request = new Request.Builder()
                .url(params.get("url"))
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Cookie", params.get("cookie"))
                .post(formBody)
                .build();

含有请求体为application/json的POST请求

 ObjectNode body = objectMapper.createObjectNode();
        body.put("lastName",lastName);
        body.put("firstName",firstName);
        body.put("gender",gender);
        Request registRequest = new Request.Builder()
                .url(endpoint+ "/注册")
                .addHeader("Authorization", token )
                .post(RequestBody.create(MediaType.parse("application/json"),objectMapper.writeValueAsString(body)))
                .build();

总结

  1. 在使用okHttp中,确保所需要的数据与请求体的类型一样。
  2. 在日常开发中,需要判断是否加Cookie和Token。
  3. 如果需要在响应体用正则获取想要的数据,判断该段数据中是否有空格分号等字符,需要单独去去除。
  4. 在与前端进行数据交互测试中,查看前端传递的参数和后端需要的参数,可能在前端输入的数据后续进行处理后进行上传。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值