android stdio 请求post,可设置header,请求各种参数


前言

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。函数会返回服务器返回的数据,以字符串形式表示。

二、测试程序

  1. 传入键值参数
    在传递键值纯文本参数时,可以将键值对放入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模拟一下服务器接收到请求的情况。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

点灯失败

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值