在java中发送post请求

创建请求工具类:

使用第三方库,如Apache HttpClient:Apache HttpClient是一个功能强大的HTTP客户端库,提供了更便捷的方式发送HTTP请求。

public class HttpRequest {
    //    发送post请求
    public JSONObject post(String url, Map data) {

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();

        //请求参数拼接JOSN字符串
        String data_s = mapToString(data);
        System.out.println(data_s);
        StringEntity entity = new StringEntity(data_s, "UTF-8");

        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(entity);
        //定义接收数据
        JSONObject result = new JSONObject();
        try {
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
        } catch (
                IOException e) {
            e.printStackTrace();
            result.put("error", "连接错误!");
        }
        //关闭连接
        try {
            client.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }
}

构建请求体

为了更好的构建请求体这里我写了一个用于将Map转换为字符串的方法。
它遍历Map中的每个键值对,将键和值以key=value的形式拼接,并用&分隔每个键值对。最后,如果字符串的长度大于0,则删除最后一个多余的&符号,然后返回拼接好的字符串。

 public static String mapToString(Map map) {
        StringBuilder stringBuilder = new StringBuilder();

        for (Map.Entry entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            stringBuilder.append(key).append("=").append(value).append("&");
        }

        // 删除最后一个"&"
        if (stringBuilder.length() > 0) {
            stringBuilder.setLength(stringBuilder.length() - 1);
        }

        return stringBuilder.toString();
    }

HttpRequest 工具类的使用示例:

public Result rtmpaddress(){
        String url = "******";
        //定义发送数据
        Map map_rtmp = new HashMap<>();
        map_rtmp.put("accessToken", "******");
        map_rtmp.put("deviceSerial", "******");
        map_rtmp.put("channelNo", "1");
        map_rtmp.put("protocol", "3");

        HttpRequest httprequest = new HttpRequest();
        JSONObject result_rtmp = httprequest.post(url,map_rtmp);
        String url_rtmp = (String) result_rtmp.getJSONObject("data").get("url");
        if (result_rtmp.get("code").equals("200")) {
            return Result.ok().data("url",url_rtmp).data("message",result_rtmp.get("msg"));
        } else {
            return Result.error().data("message",result_rtmp.get("msg"));
        }
    }

你可能感兴趣的:(java,开发语言)