Java发送POST请求:完整示例及参数说明

本文将介绍如何使用Java的HttpURLConnection类发送POST请求,并提供完整的示例代码,详细说明如何设置请求头、请求体参数,以及如何处理响应。

请求参数

  • URL:
    • 测试环境:'http://47.116.132.30:18014/g/nhjc/main/nhjcDayApi'
    • 正式环境:'http://223.244.92.80:9092/g/nhjc/main/nhjcDayApi'
  • 请求方法: POST
  • 请求头: 'content-type: application/x-www-form-urlencoded'
  • 请求体示例:
'json': {
  'username': 'root',
  'bill': {
    'year': '2022',
    'month': '01',
    'day': '02',
    'energyType': '电',
    'amount': '110.1',
    'cofficient': '0.12'
  },
  'solarEnergy': {
    'year': '2022',
    'month': '01',
    'day': '02',
    'amount': '110.1'
  }
}

说明:

  • 'json' 是上传数据的 key,固定值,不可改变。
  • 后面的JSON字符串是该日真正上传的能耗数据。

代码示例

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostRequestExample {
    public static void main(String[] args) throws IOException {
        // 请求的URL
        String url = 'http://47.116.132.30:18014/g/nhjc/main/nhjcDayApi';

        // 请求参数
        String json = '{"username":"root","bill":{"year":"2022","month":"01","day":"02","energyType":"电","amount":"110.1","cofficient":"0.12"},"solarEnergy":{"year":"2022","month":"01","day":"02","amount":"110.1"}}';

        // 创建连接
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod('POST');
        connection.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded');
        connection.setDoOutput(true);

        // 设置请求体参数
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes('json=' + json);
        outputStream.flush();
        outputStream.close();

        // 发送请求并获取响应
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 处理响应
            System.out.println(response.toString());
        } else {
            System.out.println('POST request failed. Response Code: ' + responseCode);
        }
    }
}

注意:

  • 您需要将URL和请求参数'json'替换为实际的值。
  • 此示例中的代码将发送POST请求,设置请求头为'content-type: application/x-www-form-urlencoded',并将请求体参数以'json'的key值发送。您可以根据需要进行修改和调整。

希望本文能帮助您理解如何使用Java发送POST请求。如果您有任何问题,请随时在评论区留言。

Java发送POST请求:完整示例及参数说明

原文地址: http://www.cveoy.top/t/topic/j4lI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录