1.我们都知道 表面是通过浏览器的输入http://localhost:8080/s2sh?name=nihao&age=14 就能访问服务器 但你们知道过程么
---- 其实是先把输入的URL 解析 URL u = new URL("http://localhost:8080/s2sh?name=nihao&age=14"); 可以通过url 得到一些有用的数据- URL u = new URL("http://localhost:8080/s2sh?name=nihao&age=14");
- System.out.println(u.getProtocol());
- System.out.println(u.getHost());
- System.out.println(u.getPort());
- System.out.println(u.getPath());
- System.out.println(u.getFile());
- System.out.println(u.getQuery());
- /* http
- localhost
- 8080
- /s2sh
- /s2sh?name=nihao&age=14
- name=nihao&age=14
- */
- }
复制代码 他通过URL得到的有用数据按TCP协议要求 发送给服务器 格式如下
GET / HTTP/1.1
Host: 127.0.0.1:40001
Connection: Keep-Alive
Accept: */*
Accept-Language: zh-CN
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.5072
7; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MALN; BRI/2; .NET4.0C; SE 2.X MetaSr 1.0)
Accept-Encodin
g: gzip, deflate
9; .NET CLR 3.0.30729; MALN; BRI/2; .NET4.0C; SE 2.X MetaSr 1.0)
Accept-Encodin
其实浏览器作用就是(解析URL+如下代码)(装包)- public class ClientDemo {
- public static void main(String[] args) throws Exception {
- Socket socket = new Socket("127.0.0.1", 8080);
- PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
- pw.println("GET /s2sh/index.jsp HTTP/1.1");
- pw.println("Accept: */*");
- pw.println("Accept-Language: zh-cn");
- pw.println("Host: 127.0.0.1:8080");
- pw.println("Connection: Keep-Alive");
- pw.println();
- pw.println();
- BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- String line = null;
- while ((line = br.readLine()) != null) {
- System.out.println(line);
- }
- socket.close();
- }
- }
复制代码 tomcat 服务器会返回信息
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=F6BE54A3DF5F54099A51827B15C86067; Path=/s2sh
Content-Type: text/html;charset=UTF-8
Content-Length: 753
Date: Sat, 02 Nov 2013 14:43:33 GMT
那么我们的机器又是如何处理tomcat返回的数据的呢
这时用到了URLConnection 会调用HttpURLConnection 子类 处理tomcat的返回数据 (也就是拆包)
代码如下- public class URLConnectionDemo {
- public static void main(String[] args) throws Exception {
- URL u = new URL("http://localhost:8080/s2sh?name=nihao&age=14");
- URLConnection uc = u.openConnection();
- System.out.println(uc);
- InputStream in = uc.getInputStream();
- byte[] buf = new byte[1024];
- int len = in.read(buf);
- System.out.println(new String(buf, 0, len));
- }
- }
复制代码 这样我们就能得到我们需要的数据 jsp页面 而不是带返回头信息的数据
|