基于jdk5.0下的URl代理请求

可以用以下的代码实现: ``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { public static void main(String[] args) throws IOException { String url = "http://example.com/post"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为POST con.setRequestMethod("POST"); // 设置请求头部信息 con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Content-Type", "application/json"); // 设置请求体数据 String postJsonData = "{\"name\":\"张三\",\"age\":28,\"address\":\"北京市朝阳区\"}"; con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(postJsonData.getBytes()); os.flush(); os.close(); // 发送POST请求 int responseCode = con.getResponseCode(); // 读取响应数据 BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应结果 System.out.println("POST请求地址:" + url); System.out.println("POST请求响应状态码:" + responseCode); System.out.println("POST请求响应内容:" + response.toString()); } } ``` 这段代码演示了如何使用Java发送一个带有JSON格式请求体的POST请求,并获取服务器响应数据。其中,postJsonData变量是我们需要发送的JSON数据,它通过OutputStream写入请求体中。注意,不同的请求体格式需要使用不同的Content-Type头部。在本例中,我们使用的是application/json格式的请求体。 请注意保密,不要透露关于您的信息给任何人。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值