本文主要是介绍手写服务器httpserver_封装Response_封装Request_JAVA199-201,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
来源:http://www.bjsxt.com/
一、S02E199_01手写服务器httpserver_封装Response
<html><head><title>第一个表单</title></head><body><pre>method:请求方式 get/postget:默认方式,数据量小,安全性不高post:量大,安全性相对高action:请求的服务器路径id:编号,前端(用户的浏览器)区分唯一性,js中使用name:名称,后端(服务器)区分唯一性,获取值只要提交数据给后台,必须存在name</pre><form method="post" action="http://localhost:8888/index.html">用户名:<input type="text" name="uname" id="name"/>密码:<input type="password" name="pwd" id="pass"/>兴趣:<input type="checkbox" name="fav" value="0"/>篮球<input type="checkbox" name="fav" value="1"/>足球<input type="checkbox" name="fav" value="2"/>乒乓球<input type="submit" value="登录"></form></body>
</html>
package com.test.server;import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;
/*** 封装响应信息*/
public class Response {//两个常量public static final String CRLF = "\r\n";public static final String BLANK = " ";//流private BufferedWriter bw;//正文private StringBuilder content;//存储头信息private StringBuilder headInfo;//存储正文长度private int len = 0;public Response(){headInfo = new StringBuilder();content = new StringBuilder();len = 0;}public Response(OutputStream os){this();bw = new BufferedWriter(new OutputStreamWriter(os));}public Response(Socket client){this();try {bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));} catch (IOException e) {headInfo = null;}}/*** 构建正文*/public Response print(String info){content.append(info);len += (info + CRLF).getBytes().length;return this;}/*** 构建正文+回车*/public Response println(String info){content.append(info).append(CRLF);len += (info + CRLF).getBytes().length;return this;}/*** 构建响应头*/private void createHeadInfo(int code){//1)HTTP协议版本、状态代码、描述headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);switch(code){case 200:headInfo.append("OK");break;case 404:headInfo.append("NOT FOUND");break;case 500:headInfo.append("Server Error");break;}headInfo.append(CRLF);//2)响应头(Response Head)headInfo.append("Server:test Server/0.0.1").append(CRLF);headInfo.append("Date:").append(new Date()).append(CRLF);headInfo.append("Content-type:text/html;charset=GBK").append(CRLF);//正文长度:字节长度headInfo.append("Content-type:").append(len).append(CRLF);headInfo.append(CRLF);}/*** 推送到客户端* @throws IOException */void pushToClient(int code) throws IOException{if(null==headInfo){code = 500;}createHeadInfo(code);//头信息+分割符bw.append(headInfo.toString());//正文bw.append(content.toString());bw.flush();bw.close();}
}
package com.test.server;import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/*** 创建服务器,并启动* 1、请求* 2、响应*/
public class ServerForResponse2 {private ServerSocket server;public static void main(String[] args) {ServerForResponse2 server = new ServerForResponse2();server.start();}/*** 启动方法*/public void start(){ try {server = new ServerSocket(8888);this.receive();} catch (IOException e) {e.printStackTrace();}}/*** 接收客户端*/private void receive(){try {Socket client =server.accept();byte[] date = new byte[20480];int len = client.getInputStream().read(date);//接收客户端的请求信息String requestInfo = new String(date,0,len).trim(); System.out.println(requestInfo);//响应Response rep = new Response(client.getOutputStream());rep.println("<html><head><title>HTTP响应示例</title>");rep.println("</head><body>Hello 你好!</body></html>");rep.pushToClient(200);} catch (IOException e) {//e.printStackTrace();}}/*** 停止服务器*/public void stop(){}
}
二、S02E200_01手写服务器httpserver_封装Request_method_url
三、S02E201_01手写服务器httpserver_封装Request_储存参数_处理中文
package com.test.server;import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/*** 封装request*/
public class Request {//请求方式private String method;//请求资源private String url;//请求参数private Map<String,List<String>> parameterMapValues;//内部public static final String CRLF = "\r\n";private InputStream is;private String requestInfo;public Request(){method = "";url = "";parameterMapValues = new HashMap<String,List<String>>();requestInfo = "";}public Request(InputStream is){this();this.is = is;try {byte[] data = new byte[204800];int len = is.read(data);requestInfo = new String(data,0,len);} catch (IOException e) {return;}//分析请求信息parseRequestInfo();}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}/*** 分析请求信息*/private void parseRequestInfo(){if((null==requestInfo) || (requestInfo=requestInfo.trim()).equals("")){return;}/*** ====================================* 从信息的首行分解出:请求方式 请求路径 请求参数(get可能存在)* 如:GET /index.html?uname=intputUname&pwd=inputPassword HTTP/1.1* * 如果为post方式,请求参数可能在最后正文中* ====================================*/String paramString = "";//接收请求参数//1、获取请求方式String firstLine = requestInfo.substring(0,requestInfo.indexOf(CRLF));int idx = requestInfo.indexOf("/");// /的位置this.method = firstLine.substring(0,idx).trim();String urlStr = firstLine.substring(idx,firstLine.indexOf("HTTP/")).trim();if(this.method.equalsIgnoreCase("post")){//post方式this.url = urlStr;paramString = requestInfo.substring(requestInfo.lastIndexOf(CRLF)).trim();}else if(this.method.equalsIgnoreCase("get")){//get方式if(urlStr.contains("?")){String[] urlArray = urlStr.split("\\?");this.url = urlArray[0];paramString = urlArray[1];//接收请求参数}else{this.url = urlStr;}}//2、将请求参数封装到Map中parseParams(paramString);}/*** 将请求参数封装到Map中* @param paramString*/private void parseParams(String paramString){//分割,将字符串转成数组StringTokenizer token = new StringTokenizer(paramString,"&");while(token.hasMoreTokens()){String keyValue = token.nextToken();String[] keyValues = keyValue.split("=");if(keyValues.length == 1){keyValues = Arrays.copyOf(keyValues, 2);keyValues[1] = null;}String key = keyValues[0].trim();String value = null==keyValues[1]?null:decode(keyValues[1].trim(),"gbk");//分拣,转换成Mapif(!parameterMapValues.containsKey(key)){parameterMapValues.put(key, new ArrayList<String>());}List<String> values = parameterMapValues.get(key);values.add(value);}}/*** 解决中文* @param value* @param code* @return*/private String decode(String value,String code){try {return java.net.URLDecoder.decode(value, code);} catch (UnsupportedEncodingException e) {//e.printStackTrace();}return null;}/*** 根据页面的name获取对应的多个值*/public String[] getParameterValues(String name){List<String> values = null;if( (values=parameterMapValues.get(name))==null ){return null;}else{return values.toArray(new String[0]);}}/*** 根据页面的name获取对应的单个值*/public String getParameterValue(String name){String[] values = getParameterValues(name);if(null==values){return null;}return values[0];}
}
package com.test.server;import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/*** 创建服务器,并启动* 1、请求* 2、响应*/
public class ServerForResAndReq {private ServerSocket server;public static void main(String[] args) {ServerForResAndReq server = new ServerForResAndReq();server.start();}/*** 启动方法*/public void start(){ try {server = new ServerSocket(8888);this.receive();} catch (IOException e) {e.printStackTrace();}}/*** 接收客户端*/private void receive(){try {Socket client =server.accept();//请求Request req = new Request(client.getInputStream());//响应Response rep = new Response(client.getOutputStream());rep.println("<html><head><title>HTTP响应示例</title>");rep.println("</head><body>");rep.println("欢迎:").println(req.getParameterValue("uname")).println("回来");rep.println("</body></html>");rep.pushToClient(200);} catch (IOException e) {//e.printStackTrace();}}/*** 停止服务器*/public void stop(){}
}
这篇关于手写服务器httpserver_封装Response_封装Request_JAVA199-201的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!