• 通过java.netHttpURLConnection类实现java发送http请求


    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public static String postForBody(String param) {
    try {
    URL url = new URL(“https://usapp-open.ulifecam.com”);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
    
            // 设置请求头,指示内容类型为JSON
            connection.setRequestProperty("Content-Type", "application/json");
    
            // 设置请求体
            byte[] outputInBytes = param.getBytes("UTF-8");
            int outputLength = outputInBytes.length;
    
            // 设置内容长度
            connection.setRequestProperty("Content-Length", String.valueOf(outputLength));
    
            // 默认情况下,该URLConnection的DoOutput属性为false。
            // 我们需要设置DoOutput为true,表明我们要输出数据。
            connection.setDoOutput(true);
    
            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                os.write(outputInBytes, 0, outputLength);
            }
    
            // 获取响应码
            int responseCode = connection.getResponseCode();
    
            // 根据需要获取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) { // 200
                try (java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream()))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    System.out.println("Response Body: " + response.toString());
                    return response.toString();
                }
            }
    
            // 关闭连接
            connection.disconnect();
            return null;
    
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
  • 相关阅读:
    3D-2D PNP
    【云原生&微服务五】Ribbon负载均衡策略之随机ThreadLocalRandom
    Pycharm操作git仓库 合并等
    23设计模式之 --------- 工厂模式
    进销存仓库管理系统的优势(一)
    cmd(命令行)操作或连接mysql数据库,以及创建数据库与表
    Redis之实现优惠券高并发秒杀下单
    25计算机考研院校数据分析 | 四川大学
    什么是BDD测试(行为驱动开发测试)?
    题库API搭建接口
  • 原文地址:https://blog.csdn.net/weixin_46018178/article/details/140959537