import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
    public static void main(String[] args) {
        try {
            // 创建URL对象,指定请求的地址
            URL url = new URL("http://example.com/api");
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 允许发送和接收数据
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 设置请求头(可选)
            connection.setRequestProperty("Content-Type", "application/json");
            // 发送请求数据
            String jsonInputString = "{\"key\":\"value\"}";
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);           
            }
            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}URL类创建一个表示目标服务器地址的对象。openConnection()方法打开到该URL的连接,并将其转换为HttpURLConnection对象以便进行HTTP请求。setRequestMethod()方法设置请求类型(如GET、POST等)。setDoOutput(true)和setDoInput(true)允许发送和接收数据。setRequestProperty()方法添加自定义的HTTP头信息(例如Content-Type)。getOutputStream()获取输出流并写入要发送的数据。getResponseCode()方法获取服务器返回的状态码。disconnect()方法关闭连接。如果需要更复杂的HTTP请求处理(如GET请求、处理响应内容等),可以根据需求调整代码。
上一篇:java数组合并
下一篇:java arraydeque
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站