java http协议 post请求访问地址

该代码片段展示了如何通过HttpURLConnection在Java中发送POST请求到指定的API接口地址,携带JSON数据,并处理响应结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过HttpURLConnection访问别人的接口地址

import java.io.*;
import java.net.*;
 
public class HttpTest {
    public static void main(String[] args) throws Exception {
        try{
            String jsonStr = "{\"username\":\"admin\", \"password\":\"wf2010\"}";
            // 创建连接对象
            URL url = new URL("http://192.168.10.19/dev-api/login");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            //connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 开始输入流并写入参数
            OutputStream outputStream = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(jsonStr);
            writer.flush();
            writer.close();
            outputStream.close();
            // 获取返回结果
            int responseCode = connection.getResponseCode();
            InputStream inputStream;
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
            }
            // 读取返回内容
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            reader.close();
            System.out.println("Response Code : " + responseCode);
            System.out.println("Response Message : " + stringBuilder.toString());
        }catch (Exception e){
           e.printStackTrace();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值