在Android中,从API级别30开始,DefaultHttpClient、HttpPost等类已被弃用。推荐使用HttpURLConnection或OkHttp库来替代这些类。
以下是使用HttpURLConnection的示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {
public static String doPostRequest(String urlString, String requestBody) throws IOException {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} else {
throw new IOException("HTTP request failed. Response code: " + responseCode);
}
}
}
以上代码示例中,doPostRequest方法用于发送POST请求,接收到响应后将其转换为字符串并返回。
如果你想使用OkHttp库,你需要在项目的build.gradle文件中添加以下依赖项:
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
然后,你可以使用以下示例代码:
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpClientExample {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static OkHttpClient client = new OkHttpClient();
public static String doPostRequest(String urlString, String requestBody) throws IOException {
RequestBody body = RequestBody.create(requestBody, JSON);
Request request = new Request.Builder()
.url(urlString)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
以上代码示例中,doPostRequest方法使用OkHttp发送POST请求,并返回响应体的字符串。
请根据你的具体需求选择使用HttpURLConnection或OkHttp库进行网络请求。