实现HTTP和HTTPS的网络请求库封装需要以下步骤:
导入必要的库
在Android中进行网络请求需要使用HttpURLConnection或者OkHttp库。可以在项目的gradle文件中添加以下依赖:
implementation 'com.squareup.okhttp3:okhttp:4.9.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();
}
}
实现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();
}
}
实现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();
}
}
}