如何用okhttp3进行简单的网络库封装

实现HTTP和HTTPS的网络请求库封装需要以下步骤:

  1. 导入必要的库

在Android中进行网络请求需要使用HttpURLConnection或者OkHttp库。可以在项目的gradle文件中添加以下依赖:

implementation 'com.squareup.okhttp3:okhttp:4.9.1'
  1. 创建请求类

创建一个名为HttpRequest的类,该类包含发起网络请求的方法。可以通过构造函数传递url、请求方法(GET或POST)、请求头和请求体等参数。

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequest {
    private URL url;
    private String method;
    private String contentType;
    private String data;

    public HttpRequest(String url, String method, String contentType, String data) throws IOException {
        this.url = new URL(url);
        this.method = method;
        this.contentType = contentType;
        this.data = data;
    }

    public String send() throws IOException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        if (contentType != null) {
            connection.setRequestProperty("Content-Type", contentType);
        }
        if (data != null) {
            connection.setDoOutput(true);
            OutputStream os = connection.getOutputStream();
            os.write(data.getBytes());
            os.flush();
            os.close();
        }
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            return readResponse(connection.getInputStream());
        } else {
            return readResponse(connection.getErrorStream());
        }
    }

    private String readResponse(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }
}
  1. 实现HTTP请求

创建一个名为Http的类,该类包含发送HTTP请求的方法。该类使用HttpRequest类中的send方法发起网络请求。

public class Http {
    public static String get(String url) throws IOException {
        HttpRequest request = new HttpRequest(url, "GET", null, null);
        return request.send();
    }

    public static String post(String url, String data, String contentType) throws IOException {
        HttpRequest request = new HttpRequest(url, "POST", contentType, data);
        return request.send();
    }
}
  1. 实现HTTPS请求

为了实现HTTPS请求,我们需要使用OkHttp库,并创建一个名为Https的类,该类使用OkHttp的方法发起网络请求。

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Https {
    private static final OkHttpClient client = new OkHttpClient();

    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String post(String url, RequestBody body) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值