java 网络编程 模拟browser
--java模拟实现browser,主要代码:
package socket; import java.io.*;
import java.net.*; public class MyHttpClient {
public static void main(String[] args) throws Exception{
InetAddress inet = InetAddress.getByName("localhost");
System.out.println(inet.getHostAddress());
Socket socket = new Socket(inet.getHostAddress(),6176);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
PrintWriter writer = new PrintWriter(out);
writer.println("GET / HTTP/1.1");//home.html是关于百度的页面
writer.println("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
writer.println("Accept-Language: en-us,zh-cn;q=0.5");
writer.println("Accept-Encoding: gzip, deflate");
writer.println("Host: wwdddw.baidu.com");
writer.println("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
writer.println("Connection: Keep-Alive");
writer.println();
writer.flush();
String line = reader.readLine();
while(line!=null){
//System.out.println(line.length());
System.out.println(line);
line = reader.readLine();
}
reader.close();
writer.close();
}
}
MyHttpClient
package socket; import java.io.*;
import java.net.*;
/**
* MyHttpServer 实现一个简单的HTTP服务器端,可以获取用户提交的内容
* 并给用户一个response
* 因为时间的关系,对http头的处理显得不规范
* 对于上传附件,暂时只能解析只上传一个附件而且附件位置在第一个的情况
* 转载请注明来自http://blog.csdn.net/sunxing007
* **/
public class MyHttpServer {
//服务器根目录,post.html, upload.html都放在该位置
public static String WEB_ROOT = "c:/root";
//端口
private int port;
//用户请求的文件的url
private String requestPath;
//mltipart/form-data方式提交post的分隔符,
private String boundary = null;
//post提交请求的正文的长度
private int contentLength = 0; public MyHttpServer(String root, int port) {
WEB_ROOT = root;
this.port = port;
requestPath = null;
}
//处理GET请求
private void doGet(DataInputStream reader, OutputStream out) throws Exception {
if (new File(WEB_ROOT + this.requestPath).exists()) {
//从服务器根目录下找到用户请求的文件并发送回浏览器
InputStream fileIn = new FileInputStream(WEB_ROOT + this.requestPath);
byte[] buf = new byte[fileIn.available()];
fileIn.read(buf);
out.write(buf);
out.close();
fileIn.close();
reader.close();
System.out.println("request complete.");
}
}
//处理post请求
private void doPost(DataInputStream reader, OutputStream out) throws Exception {
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
if ("".equals(line)) {
break;
} else if (line.indexOf("Content-Length") != -1) {
this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));
}
//表明要上传附件, 跳转到doMultiPart方法。
else if(line.indexOf("multipart/form-data")!= -1){
//得multiltipart的分隔符
this.boundary = line.substring(line.indexOf("boundary") + 9);
this.doMultiPart(reader, out);
return;
}
}
//继续读取普通post(没有附件)提交的数据
System.out.println("begin reading posted data......");
String dataLine = null;
//用户发送的post数据正文
byte[] buf = {};
int size = 0;
if (this.contentLength != 0) {
buf = new byte[this.contentLength];
while(size<this.contentLength){
int c = reader.read();
buf[size++] = (byte)c; }
System.out.println("The data user posted: " + new String(buf, 0, size));
}
//发送回浏览器的内容
String response = "";
response += "HTTP/1.1 200 OK/n";
response += "Server: Sunpache 1.0/n";
response += "Content-Type: text/html/n";
response += "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n";
response += "Accept-ranges: bytes";
response += "/n";
String body = "<html><head><title>test server</title></head><body><p>post ok:</p>" + new String(buf, 0, size) + "</body></html>";
System.out.println(body);
out.write(response.getBytes());
out.write(body.getBytes());
out.flush();
reader.close();
out.close();
System.out.println("request complete.");
}
//处理附件
private void doMultiPart(DataInputStream reader, OutputStream out) throws Exception {
System.out.println("doMultiPart ......");
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
if ("".equals(line)) {
break;
} else if (line.indexOf("Content-Length") != -1) {
this.contentLength = Integer.parseInt(line.substring(line.indexOf("Content-Length") + 16));
System.out.println("contentLength: " + this.contentLength);
} else if (line.indexOf("boundary") != -1) {
//获取multipart分隔符
this.boundary = line.substring(line.indexOf("boundary") + 9);
}
}
System.out.println("begin get data......");
/*下面的注释是一个浏览器发送带附件的请求的全文,所有中文都是说明性的文字*****
<HTTP头部内容略>
............
Cache-Control: no-cache
<这里有一个空行,表明接下来的内容都是要提交的正文>
-----------------------------7d925134501f6<这是multipart分隔符>
Content-Disposition: form-data; name="myfile"; filename="mywork.doc"
Content-Type: text/plain <附件正文>........................................
................................................. -----------------------------7d925134501f6<这是multipart分隔符>
Content-Disposition: form-data; name="myname"<其他字段或附件>
<这里有一个空行>
<其他字段或附件的内容>
-----------------------------7d925134501f6--<这是multipart分隔符,最后一个分隔符多两个->
****************************************************************/
/**
* 上面的注释是一个带附件的multipart类型的POST的全文模型,
* 要把附件去出来,就是要找到附件正文的起始位置和结束位置
* **/
if (this.contentLength != 0) {
//把所有的提交的正文,包括附件和其他字段都先读到buf.
byte[] buf = new byte[this.contentLength];
int totalRead = 0;
int size = 0;
while (totalRead < this.contentLength) {
size = reader.read(buf, totalRead, this.contentLength - totalRead);
totalRead += size;
}
//用buf构造一个字符串,可以用字符串方便的计算出附件所在的位置
String dataString = new String(buf, 0, totalRead);
System.out.println("the data user posted:/n" + dataString);
int pos = dataString.indexOf(boundary);
//以下略过4行就是第一个附件的位置
pos = dataString.indexOf("/n", pos) + 1;
pos = dataString.indexOf("/n", pos) + 1;
pos = dataString.indexOf("/n", pos) + 1;
pos = dataString.indexOf("/n", pos) + 1;
//附件开始位置
int start = dataString.substring(0, pos).getBytes().length;
pos = dataString.indexOf(boundary, pos) - 4;
//附件结束位置
int end = dataString.substring(0, pos).getBytes().length;
//以下找出filename
int fileNameBegin = dataString.indexOf("filename") + 10;
int fileNameEnd = dataString.indexOf("/n", fileNameBegin);
String fileName = dataString.substring(fileNameBegin, fileNameEnd);
/**
* 有时候上传的文件显示完整的文件名路径,比如c:/my file/somedir/project.doc
* 但有时候只显示文件的名字,比如myphoto.jpg.
* 所以需要做一个判断。
*/
if(fileName.lastIndexOf("//")!=-1){
fileName = fileName.substring(fileName.lastIndexOf("//") + 1);
}
fileName = fileName.substring(0, fileName.length()-2);
OutputStream fileOut = new FileOutputStream("c://" + fileName);
fileOut.write(buf, start, end-start);
fileOut.close();
fileOut.close();
}
String response = "";
response += "HTTP/1.1 200 OK/n";
response += "Server: Sunpache 1.0/n";
response += "Content-Type: text/html/n";
response += "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n";
response += "Accept-ranges: bytes";
response += "/n";
out.write("<html><head><title>test server</title></head><body><p>Post is ok</p></body></html>".getBytes());
out.flush();
reader.close();
System.out.println("request complete.");
} public void service() throws Exception {
ServerSocket serverSocket = new ServerSocket(this.port);
System.out.println("server is starting up.");
System.out.println("server is ok.");
//开启serverSocket等待用户请求到来,然后根据请求的类别作处理
//在这里我只针对GET和POST作了处理
//其中POST具有解析单个附件的能力
while (true) {
Socket socket = serverSocket.accept();
System.out.println("new request coming.");
DataInputStream reader = new DataInputStream((socket.getInputStream()));
String line = reader.readLine();
String method = line.substring(0, 4).trim();
OutputStream out = socket.getOutputStream();
this.requestPath = line.split(" ")[1];
System.out.println(method);
if ("GET".equalsIgnoreCase(method)) {
System.out.println("do get......");
this.doGet(reader, out);
} else if ("POST".equalsIgnoreCase(method)) {
System.out.println("do post......");
this.doPost(reader, out);
}
socket.close();
System.out.println("socket closed.");
}
}
public static void main(String args[]) throws Exception {
MyHttpServer server = new MyHttpServer("D:/dev/ws/myeclipse10.7/socket/page", 8080);
server.service();
}
}
MyHttpServer
java 网络编程 模拟browser的更多相关文章
- Java网络编程(模拟浏览器访问Tomcat服务器)
程序运行结果: HTTP/1.1 404 Not FoundServer: Apache-Coyote/1.1Content-Type: text/html;charset=utf-8Content- ...
- Java 网络编程 -- 基于TCP 模拟多用户登录
Java TCP的基本操作参考前一篇:Java 网络编程 – 基于TCP实现文件上传 实现多用户操作之前先实现以下单用户操作,假设目前有一个用户: 账号:zs 密码:123 服务端: public c ...
- JAVA网络编程【转】出处不详
网络编程 网络编程对于很多的初学者来说,都是很向往的一种编程技能,但是很多的初学者却因为很长一段时间无法进入网络编程的大门而放弃了对于该部分技术的学习. 在 学习网络编程以前,很多初学者可能觉得网络编 ...
- 【转】JAVA 网络编程
网络编程 网络编程对于很多的初学者来说,都是很向往的一种编程技能,但是很多的初学者却因为很长一段时间无法进入网络编程的大门而放弃了对于该部分技术的学习. 在 学习网络编程以前,很多初学者可能觉得网络编 ...
- java网络编程+通讯协议的理解
参考: http://blog.csdn.net/sunyc1990/article/details/50773014 网络编程对于很多的初学者来说,都是很向往的一种编程技能,但是很多的初学者却因为很 ...
- Java网络编程学习笔记
Java网络编程,我们先来看下面这一张图: 由图可得:想要进行网络编程,首先是服务器端通过ServerSocket对某一个端口进行监听.通过accept来判断是否有客户端与其相连.若成功连上,则通过r ...
- Java 网络编程初探
Java 网络编程 网络编程 网络编程:进行服务器端与客户端编程的开发操作实现. java.net:网络操作包 B/S结构: 浏览器/服务器模式(Browser/Server) 不在开发客户端代码 开 ...
- JAVA网络编程入门
JAVA网络编程入门 软件结构 C/S结构 B/S结构 无论哪一种结构,都离不开网络的支持.网络编程,就是在网络的条件下实现机器间的通信的过程 网络通信协议 网络通信协议:通信双方必须同时遵守才能完成 ...
- Java网络编程与NIO详解10:深度解读Tomcat中的NIO模型
本文转自:http://www.sohu.com/a/203838233_827544 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 ht ...
随机推荐
- 应用数据存储到sdcard上一定要规范,android4.4.2有新规范
如果你的android设备有内部存储空间,即通常所说的机身存储(这就是指主要外部存储),那么你从外部插入SD卡就是一个二级外部存储设备. 最新的Android 4.4系统中,外置存储卡(SD卡)被称为 ...
- openstack deug
今天想debug一下nova-compute进程, 用devstack迅速安装之后, kill掉nova-compute进程,然后修改nova/cmd/__init__.py文件的 “eventlet ...
- Java处理InterruptedException异常小结
对于InterruptedException,一种常见的处理方式是捕捉它,然后什么也不做(或者记录下它,不过这也好不到哪去).不幸的是,这种方法忽略了这样一个事实:这期间可能发生中断,而中断可能导致应 ...
- 【转】linux代码段,数据段,BSS段, 堆,栈
转载自 http://blog.csdn.net/wudebao5220150/article/details/12947445 linux代码段,数据段,BSS段, 堆,栈 网上摘抄了一些,自己组 ...
- Win7下使Users数据与程序分离
大家知道,数据是用户最大的财富,但Windows系统默认的模式是将所有软件都安装在C盘,在Windows XP时代,数据文件夹会放在Document And Setting 目录下,在Win7时代,数 ...
- C++问题-无法打开某个自定义源文件
问题经过:需要做一个工具,是在某个产品的基础上做的,所以要来了同事的代码.用VS打开后,提示如下问题.1>c1xx : fatal error C1083: 无法打开源文件:“..\..\GUX ...
- Android问题-DelphiXE8安装后编译Android提示SDK无法更新问题(XE10也可以解决)
资料来原:http://www.chenruixuan.com/archives/479.html (DelphiXE8 更新SDK)http://www.dfwlt.com/forum.php?mo ...
- HDU 4597 Play Game (DP,记忆化搜索,博弈)
题意:Alice和Bob玩一个游戏,有两个长度为N的正整数数字序列,每次他们两个,只能从其中一个序列,选择两端中的一个拿走.他们都希望可以拿到尽量大的数字之和, 并且他们都足够聪明,每次都选择最优策略 ...
- C#学习笔记(五):泛型
认识泛型 泛型使类型参数化,从而实现了算法上的代码重用. 同时由于去掉了转换中装箱和拆箱的操作,使用泛型还可以提高程序的运行速度. 我们先看看C#自带的使用了泛型的类: using System.Co ...
- UVa657 The die is cast
// 题意:给一个图案,其中'.'表示背景,非'.'字符组成的连通块为筛子.每个筛子里又包含两种字符,其中'X'组成的连通块表示筛子上的点 // 统计每个筛子里有多少个"X"连通块 ...