java 发送http post请求 参数为list或者 map

Java发送HTTP POST请求非常常见和简单,可以使用HttpURLConnection或HttpClient来实现。获取返回的请求头header也很简单,只需要在发送请求后使用getResponseHeader()或getAllHeaders()方法获取即可。 以HttpURLConnection为例,发送POST请求并获取返回的请求头header的代码如下: ``` URL url = new URL("http://www.example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(jsonString.getBytes()); os.flush(); // 获取返回的请求头header Map<String, List<String>> headers = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String key = entry.getKey(); List<String> values = entry.getValue(); System.out.println(key + ": " + values); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); os.close(); conn.disconnect(); ``` 上述代码中,首先创建了一个URL和HttpURLConnection对象,然后设置POST请求的Content-Type,将请求体写入输出流中,并发送请求。接着使用conn.getHeaderFields()方法获取返回的请求头header并遍历输出。最后读取返回的响应体并关闭连接。 需要注意的是,如果返回的响应头中有多个值,则可以用getList()方法获取并输出。此外,如果需要在请求头中添加自定义的header,则可以使用setRequestProperty()方法来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值