前言
android stdio 请求post,可设置header,请求各种参数
一、示例函数
public static String sendPostRequest(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置header
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 设置参数
if (parameters != null) {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
}
String params = stringBuilder.toString();
byte[] postData = params.getBytes("UTF-8");
connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(postData);
}
}
// 获取响应结果
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} else {
throw new IOException("服务器返回错误,状态码:" + statusCode);
}
} finally {
// 关闭连接和流
if (reader != null) {
reader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
}
return buffer.toString();
}
这个函数接收三个参数:
- url:要访问的url
- parameters:post请求的参数,是一个键值对map
- headers:post请求的header,也是一个键值对map
如果不需要设置参数或header,则可以传入null。函数会返回服务器返回的数据,以字符串形式表示。
二、测试程序
- 传入键值参数
在传递键值纯文本参数时,可以将键值对放入Map中,发送请求时使用sendPostRequest()函数即可。例如:
public static void main(String[] args) {
String url = "https://httpbin.org/post";
Map<String, String> parameters = new HashMap<>();
parameters.put("name", "binjie09");
parameters.put("age", "25");
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0");
try {
String response = sendPostRequest(url, parameters, headers);
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
可以用Postman模拟一下服务器接收到请求的情况。