您的位置:首页 > 其它

使用Socket发送GET/POST请求

2015-06-30 06:42 267 查看
最近需要模拟客户端向服务器发送数据,弄清楚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("H
4000
ost: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提交的数据都可以看到了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  socket 服务器