使用Socket发送GET/POST请求

最近需要模拟客户端向服务器发送数据,弄清楚GET/POST两种提交方式的实现。用MyEclipse模拟HTTP Client,登录到一个服务器。

package a;


import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import org.apache.commons.io.IOUtils;
import org.junit.Test;


public class Demo1 {
/**
* 使用Socket发送GET请求。

* @throws Exception
*/
@Test
public void fun1() throws Exception {
// 连接localhost主机,
Socket s = new Socket("localhost", 80);
// 向服务器发送数据。
/*
* GET /day03_2/sayhello.jsp HTTP/1.1 Host: localhost Connection:
* keep-alive //连接一小会儿
*/
// 获取可以向服务器发送数据的输出流对象。
PrintStream out = new PrintStream(s.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append(
"GET /day03_2/sayhello.jsp?username=zhangSan&password=123 HTTP/1.1 ")
.append("\r\n");
sb.append("Host: localhost").append("\r\n");
sb.append("Connection: close").append("\r\n"); // 连接方式:响应后立刻断开。
sb.append("\r\n"); // 换行
out.print(sb.toString());


// 获取服务器
InputStream in = s.getInputStream();
String str = IOUtils.toString(in);// 读取输入流中的数据,转换成字符串。
System.out.println(str);
}

/**
* 使用Socket发送POST
*/
@Test
public void fun2() throws Exception {
/*
* POST /hello/index.jsp HTTP/1.1 Content-Type:
* application/x-www-form-urlencoded Host: localhost Content-Length: 12
* Connection: close username=zhangSan&password=123
*/
// 连接localhost主机,
Socket s = new Socket("localhost", 80);
// 向服务器发送数据。
/*
* POST /day03_1/sayhello.jsp HTTP/1.1 Host: localhost Connection:
* keep-alive //连接一小会儿
*/
String text = "username=zhangSan&password=123";// 要发送的数据
// 获取可以向服务器发送数据的输出流对象。
PrintStream out = new PrintStream(s.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append("POST /day03_1/sayhello.jsp HTTP/1.1 ").append("\r\n");
sb.append("Host: localhost").append("\r\n");
// 指定数据类型为URL编码,这是POST的一大特性。
sb.append("Content-Type: application/x-www-form-urlencoded").append(
"\r\n");
// 指定请求体的长度,必须是正确的。
sb.append("Content-Length: " + text.length()).append("\r\n");
sb.append("Connection: close").append("\r\n"); // 连接方式:响应后立刻断开。
sb.append("\r\n"); // 换行
// 在空行后面给出请求体的内容。
sb.append("text").append("\r\n");
out.print(sb.toString());


// 获取服务器
InputStream in = s.getInputStream();
String str = IOUtils.toString(in);// 读取输入流中的数据,转换成字符串。
System.out.println(str);
}
}

开启Tomcat后,对fun1进行单元测试,控制台报错:

HTTP/1.1 505 HTTP Version Not Supported
Server: Apache-Coyote/1.1
Date: Mon, 29 Jun 2015 22:24:37 GMT
Connection: close

开始,我以为是自己当时的HTTP/1.1不能在MyEclipse10中使用或者我的Tomcat版本不兼容HTTP/1.1。

通过查找资料,发现HTTP写的格式是非常严谨的,只要格式不匹配,就会报错误。

故而推断我发送的字符串消息中可能某些地方多了空格。在去掉一些字符串消息的空格后,fun1()代码如下

@Test
public void fun1() throws Exception {
// 连接localhost主机,
Socket s = new Socket("localhost", 80);
// 向服务器发送数据。
/*
* GET /day03_2/sayhello.jsp HTTP/1.1 Host: localhost Connection:
* keep-alive //连接一小会儿
*/
// 获取可以向服务器发送数据的输出流对象。
PrintStream out = new PrintStream(s.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append("GET /day03_2/sayhello.jsp?username=zhangSan&password=123 HTTP/1.1").append("\r\n");
sb.append("Host:localhost").append("\r\n");
sb.append("Connection:close").append("\r\n"); // 连接方式:响应后立刻断开。
sb.append("\r\n"); // 换行
out.print(sb.toString());

// 获取服务器
InputStream in = s.getInputStream();
String str = IOUtils.toString(in);// 读取输入流中的数据,转换成字符串。
System.out.println(str);
}

再进行fun1()测试时,控制台出现

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=CF2DC6448C49230F965C5BEADB2EA0A5; Path=/day03_2/; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 676
Date: Mon, 29 Jun 2015 23:02:58 GMT
Connection: close








<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://localhost:80/day03_2/">
    
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
  
  <body>
      <h1>Say Hello!</h1>
      <h3>您好: zhangSan,您的密码是:123</h3>
  </body>
</html>

终于看到发送的一些数据了。

同样,fun2()也去除一些空格。如下

@Test
public void fun2() throws Exception {
/*
* POST /hello/index.jsp HTTP/1.1 Content-Type:
* application/x-www-form-urlencoded Host: localhost Content-Length: 12
* Connection: close username=zhangSan&password=123
*/
// 连接localhost主机,
Socket s = new Socket("localhost", 80);
// 向服务器发送数据。
/*
* POST /day03_2/sayhello.jsp HTTP/1.1 Host: localhost Connection:
* keep-alive //连接一小会儿
*/
String text = "username=zhangSan&password=123";// 要发送的数据
// 获取可以向服务器发送数据的输出流对象。
PrintStream out = new PrintStream(s.getOutputStream());
StringBuilder sb = new StringBuilder();
sb.append("POST /day03_2/sayhello.jsp HTTP/1.1").append("\r\n");
sb.append("Host:localhost").append("\r\n");
// 指定数据类型为URL编码,这是POST的一大特性。
sb.append("Content-Type:application/x-www-form-urlencoded").append(
"\r\n");
// 指定请求体的长度,必须是正确的。
sb.append("Content-Length: " + text.length()).append("\r\n");
sb.append("Connection: close").append("\r\n"); // 连接方式:响应后立刻断开。
sb.append("\r\n"); // 换行
// 在空行后面给出请求体的内容。
sb.append("text").append("\r\n");
out.print(sb.toString());

// 获取服务器
InputStream in = s.getInputStream();
String str = IOUtils.toString(in);// 读取输入流中的数据,转换成字符串。
System.out.println(str);
}
}

单元测试时,控制台显示:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=71A49BDC2016449A3CD2794A58921855; Path=/day03_2/; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 665
Date: Mon, 29 Jun 2015 23:13:03 GMT
Connection: close








<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://localhost:80/day03_2/">
    
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
  
  <body>
      <h1>Say Hello!</h1>
      <h3>您好: ,您的密码是:</h3>
  </body>
</html>

到此,Socket通过GET/POST提交的数据都可以看到了。微笑

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值