HttpURLConnection模拟请求小例子

本文详细介绍了如何使用HttpURLConnection类来访问HTTP资源。包括创建连接、设置请求参数、连接及使用输入输出流传递参数等步骤。

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

HttpURLConnection用法详解

一、简介

HttpURLConnection类是另一种访问HTTP资源的方式。

二、连接步骤

1、通过openConnection方法创建连接对象。

2、设置请求头和请求体

3、使用connect方法于远程对象进行连接

4、远程对象变得可用,其字段和内容变得可访问

三、用法

1、创建连接

// 获取连接的URL

URLurl= newURL("http://localhost:8080/day10-http/ServletDemo1");

// 打开连接

HttpURLConnectionhttp= (HttpURLConnection) url.openConnection();


2、设置请求参数

//提交模式,默认是“GET”

conn.setRequestMethod("POST"); //提交模式

//设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在

//http正文内,因此需要设为true,默认情况下是false;

conn.setDoOutput(true);

//设置是否从httpUrlConnection读入,默认情况下是true;

conn.setDoInput(true);

//Post 请求不能使用缓存

conn.setUseCaches(false);

//设定传送的内容类型是可序列化的java对象

//(如果不设此项,在传送序列化对象时,WEB服务默认的不是这种类型时可能抛java.io.EOFException)

//conn.setRequestProperty("Content-type","application/x-java-serialized-object");

conn.setRequestProperty("Content-Type","application/json;charset=UTF-8"); //设置请求属性

conn.setRequestProperty("User-Agent","Autoyol_gpsCenter");

//连接,从上述中url.openConnection()至此的配置必须要在connect之前完成,


3、连接

conn.connect();

4、使用输入输出流传递参数

Stringstr= "{\"name\":\"小李\"}";

OutputStream os = conn.getOutputStream();

os.write(str.getBytes());

os.flush();

os.close();

//如果我将此段放在if里面,那么他会爆出不能将输出放在输入之后的问题,将其放在外面就OK

if(conn.getResponseCode()==200){

InputStreamis= conn.getInputStream();

byte[]buffer= newbyte[1024];

ByteArrayOutputStreambaos= newByteArrayOutputStream();

for(intlen=0;(len= is.read(buffer))>0;){

baos.write(buffer,0, len);

}

StringreturnValue= newString(baos.toByteArray(),"utf-8");

System.out.println(returnValue);

baos.flush();

baos.close();

is.close();

}

servlet

request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        response.getWriter().write("hello");
        InputStream is = request.getInputStream();
        byte[] buffer = new byte[1024];
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         for(int len =0;(len = is.read(buffer))>0;) {
             baos.write(buffer, 0, len);
         }
         String returnValue = new String(baos.toByteArray(), "utf-8" );
         System.out.println(returnValue);
         baos.flush();
         baos.close();
         is.close();



### Java 实现 POST 请求 为了使用 Java 模拟浏览器发送 POST 请求,`HttpURLConnection` 是一种常用的方式。下面是一个完整的例子来展示如何构建并发送带有参数的 HTTP POST 请求[^1]。 ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class PostExample { private final String USER_AGENT = "Mozilla/5.0"; public static void main(String[] args) throws Exception { new PostExample().sendPost(); } // 发送POST请求到给定URL public void sendPost() throws Exception { String url = "http://example.com/api"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置基本属性 con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // 设置为true表示允许输入和输出流操作 con.setDoOutput(true); // 构建表单数据字符串 String urlParameters = "param1=value1&param2=value2"; // 发送POST请求中的参数 try(OutputStream os = con.getOutputStream()) { byte[] input = urlParameters.getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = con.getResponseCode(); System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应 // 处理成功后的逻辑... } else { // 错误处理... } } } ``` 此代码片段展示了创建 `HttpURLConnection` 对象的过程,并设置了必要的头部信息以及通过输出流写入要传递的数据。注意这里指定了 User-Agent 字符串模仿真实浏览器行为[^4]。此外,在设置连接对象时启用了输出模式 (`setDoOutput`) 来准备发送数据。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值