是的,Android 应用可以发起 HTTPS 请求。Android 提供了多种方式来执行 HTTP 或 HTTPS 请求,常用的方式有:
1. 使用 `HttpURLConnection` 类:
这是 Android 中原生提供的网络请求类,用来发送 HTTP 或 HTTPS 请求。以下是一个简单的例子:
```java
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public void sendRequest() {
try {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000); // 连接超时
connection.setReadTimeout(5000); // 读取超时
// 获取响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用 `OkHttp` 库:
`OkHttp` 是一个第三方的网络请求库,提供了简洁的 API,并且支持 HTTPS 请求。它比 `HttpURLConnection` 更加灵活和强大。
在 `build.gradle` 文件中添加依赖:
```gradle
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
```
然后在代码中使用如下:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpExample {
public void sendRequest() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3. 使用 `Retrofit` 库:
`Retrofit` 是一个更高层次的网络请求库,基于 `OkHttp`,适合与 REST API 交互。它简化了网络请求的构建和处理。
在 `build.gradle` 文件中添加依赖:
```gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
```
使用示例如下:
```java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class RetrofitExample {
public void sendRequest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call
call.enqueue(new Callback
@Override
public void onResponse(Call
if (response.isSuccessful()) {
System.out.println(response.body());
}
}
@Override
public void onFailure(Call
t.printStackTrace();
}
});
}
}
```
无论使用哪种方法,都可以通过设置 URL 地址为 HTTPS 协议来发起 HTTPS 请求。需要注意,使用 HTTPS 请求时,服务器端需要支持 HTTPS 协议并且配置有效的 SSL/TLS 证书。