OkHttp的基本使用

本文介绍了OkHttp的基础使用方法,包括创建 OkHttpClient 实例、发起HTTP请求、处理响应等关键步骤。
摘要由CSDN通过智能技术生成

OkHttp的基本使用

package com.dgy;

import okhttp3.*;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * (๑•.•๑)   ٩(⑉Ծ^Ծ⑉)ᕗ   _(•̀ω•́ 」∠)_
 * Date&Time: 2020/10/9 周五 17:02
 * Author: GuangYao-Dou
 * Description:
 */

public class TestRequest {

    private static final String BASE_URL = "http://localhost:8080";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 无参请求
     *      空请求体
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/test2").newBuilder();
        RequestBody requestBody = RequestBody.create(JSON, "");
        Request request = new Request.Builder().url(urlBuilder.build()).post(requestBody).build();
        Response execute = new OkHttpClient().newCall(request).execute();
        System.out.println(execute.body().string());
    }

    /**
     * 携带请求头
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/test3").newBuilder()
                .addQueryParameter("date", "2018/1/1");
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .get()
                .header("token", "hello")
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());
        System.out.println(response.header("Content-Type"));
        System.out.println(response.header("Date"));
        System.out.println(response.header("Connection"));
    }

    /**
     * 携带请求体
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/test4").newBuilder()
                .addQueryParameter("number", "8552");
        Student student1 = new Student();
        student1.setAge(58);
        student1.setName("hello");
        Request request = new Request.Builder()
                .post(FormBody.create(JSON, com.alibaba.fastjson.JSON.toJSONString(student1)))
                .url(urlBuilder.build())
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());
    }

    /**
     * 携带请求头、 请求体
     * @throws IOException
     */
    @Test
    public void test5() throws IOException {
        HttpUrl.Builder urlBuiler = HttpUrl.parse(BASE_URL + "/test5")
                .newBuilder()
                .addQueryParameter("name", "dgy")
                .addQueryParameter("age", "25");
        Student student = new Student();
        student.setName("stu");
        student.setAge(12);
        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(6);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("stu", student);
        System.out.println(com.alibaba.fastjson.JSON.toJSONString(map));
        Request request = new Request.Builder()
                .header("token", "tokendfghjkl;")
                .post(RequestBody.create(JSON, com.alibaba.fastjson.JSON.toJSONString(map)))
                .url(urlBuiler.build())
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());
    }


    //异步请求
    @Test
    public void test6() {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/test3")
                .newBuilder()
                .addQueryParameter("date", "2020-1-1");
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .get()
                .header("token", "mytest3token")
                .build();
        Call call = new OkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败了");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功" + response.body().string());
            }
        });
    }

    //表单请求
    @Test
    public void test7() throws IOException {
        HttpUrl httpUrl = HttpUrl.parse(BASE_URL + "/test6")
                .newBuilder().build();
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("id", "22755")
                .addFormDataPart("pwd", "dgyu177")
                .build();
        RequestBody body1 = new FormBody.Builder()
                .add("id", "22755")
                .add("pwd", "djlkjll")
                .build();
        Request request = new Request.Builder()
                .url(httpUrl)
                .post(body1)
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response.body().string());
    }

    /**
     * 上传文件
     * @throws IOException
     */
    @Test
    public void test8() throws IOException {
        HttpUrl httpUrl = HttpUrl.parse(BASE_URL + "/test7")
                .newBuilder().build();
        RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "jjj.png",
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                new File("F:\\图片\\1920x1080_px_Dark_Ens_fish_minimalism_red-1299857.jpg")))
                .build();
        Request request = new Request.Builder()
                .url(httpUrl)
                .post(body)
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        System.out.println(response);
        System.out.println(response.body().string());
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值