1 --get提交
2
3 //资源url地址
4 URL url = new URL("http://localhost:8080/test/TestServlet?id=10");
5 //获取连接对象
6 URLConnection conn = url.openConnection();
7 //设置连接时间,可省略
8 conn.setConnectTimeout(5*1000);
9 //设置可以接受InputStream流,默认true
10 //conn.setDoInput(true);
11
12 //建立连接,可省略,因为真正的连接是在getInputStream()方法中开始的
13 //conn.connect();
14
15 //发送请求参数,并且获取响应信息
16 InputStream inputStream = conn.getInputStream();
17 //相应信息保存
18 OutputStream out = new FileOutputStream("e:/ss.jpg");
19 byte[] buf = new byte[1024];
20 int len = 0;
21 while ((len = inputStream.read(buf)) != -1) {
22 // out.write(buf, 0, len);
23 System.out.println(new String(buf, 0, len));
24 }
25
26 //关闭资源
27 inputStream.close();
28 out.close();
结果:
10
--post提交
//资源url地址
URL url = new URL("http://localhost:8080/test/TestServlet);
//获取连接对象
URLConnection conn = url.openConnection();
//设置连接时间,可省略
conn.setConnectTimeout(5*1000);
//设置可以接受InputStream流,默认true
//conn.setDoInput(true);
//设置输出流,写入post体
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write("name=yyq2".getBytes());
outputStream.close();
//建立连接,可省略,因为真正的连接是在getInputStream()方法中开始的
//conn.connect();
//发送请求参数,并且获取响应信息
InputStream inputStream = conn.getInputStream();
//相应信息保存
OutputStream out = new FileOutputStream("e:/ss.jpg");
byte[] buf = new byte[1024];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
// out.write(buf, 0, len);
System.out.println(new String(buf, 0, len));
}
//关闭资源
inputStream.close();
out.close();
结果:
yyq2