在Android中动态传递POST、GET等方法类型,可以通过使用HttpURLConnection或者OkHttp库来实现。下面是一个示例代码:
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;
import java.net.URLEncoder;
public class HttpUtils {
public static String sendRequest(String url, String method, String params) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod(method);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoInput(true);
connection.setDoOutput(true);
if (method.equals("POST")) {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
outputStream.close();
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
}
使用示例:
String url = "http://example.com/api";
String method = "POST";
String params = "param1=value1¶m2=value2";
String response = HttpUtils.sendRequest(url, method, params);
首先,在项目的build.gradle文件中添加OkHttp库的依赖:
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}
然后,使用以下代码发送请求:
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpUtils {
public static String sendRequest(String url, String method, String params) {
OkHttpClient client = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url(url);
if (method.equals("POST")) {
RequestBody requestBody = new FormBody.Builder()
.add("param1", "value1")
.add("param2", "value2")
.build();
requestBuilder.post(requestBody);
}
Request request = requestBuilder.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
使用示例:
String url = "http://example.com/api";
String method = "POST";
String params = "param1=value1¶m2=value2";
String response = HttpUtils.sendRequest(url, method, params);
以上代码示例中,我们通过HttpURLConnection和OkHttp库分别实现了在Android中动态传递POST和GET方法类型的请求。在使用时,只需要提供请求的URL、请求方法和参数即可。
领取专属 10元无门槛券
手把手带您无忧上云