HttpURLConnection使用基本操作

本文详细介绍了如何使用Java的HttpURLConnection类发送HTTPGET和POST请求,涉及参数设置、header、Cookie管理以及获取响应数据的过程。

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

http请求 一般包括 请求参数/header/cookie等参数的设置。

下面使用 HttpURLConnection发起http请求 的基本操作,再复杂的 http客户端,最终都是完成这些基本操作:

URL console = new URL(url);
HttpURLConnection conn = (HttpURLConnection) console.openConnection();


// GET/POST
conn.setRequestMethod(requestMethod);

conn.setDoOutput(true);
conn.setDoInput(true);

conn.setConnectTimeout(3*1000);
conn.setReadTimeout(30*1000);


// 设置header
conn.setRequestProperty("Content-Type", "application/json");

// 设置cookie ,多个cookie 用 ; 连接,如: c1=v2;c2=v2
conn.setRequestProperty("Cookie", cookieHeader);

// 建立连接
conn.connect();


// 设置请求参数:写入body 参数,get 请求不能写参数
OutputStream outputStream = conn.getOutputStream();
outputStream.write(param.getBytes());

// 发起请求
conn.getResponseCode();

// 获取响应数据
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null) {
    if (ret != null && !ret.trim().equals("")) {
        result.append(new String(ret.getBytes("utf-8"), "utf-8"));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值