javawebserver-获取参数和处理中文

Server:

创新互联是一家专业提供霍州企业网站建设,专注与成都做网站、成都网站制作、H5场景定制、小程序制作等业务。10年已为霍州众多企业、政府机构等服务。创新互联专业网络公司优惠进行中。

public class Server04 {
        private ServerSocket serverSocket ;
        public static void main(String[] args) {
                Server04 server = new Server04();
                server.start();
        }
        //启动服务
        public void start() {
                try {
                        serverSocket =  new ServerSocket(8888);
                         receive();
                } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("服务器启动失败....");
                }
        }
        //接受连接处理
        public void receive() {
                try {
                        Socket client = serverSocket.accept();
                        System.out.println("一个客户端建立了连接....");
                        //获取请求协议

    Request request=new Request(client);

    //关注了内容
    Response response=new Response(client); //创建好了输出流
    response.print("");    //通过输出流输出
    response.print("");
    response.print("");
    response.print("服务器响应成功");
    response.print("");
    response.print("");
    response.print("");
    response.print("shsxt server终于回来了。。。。"+request.getParameter("uname"));
    response.print("");
    response.print("");
    //关注了状态码
    response.pushToBrowser(200);

} catch (IOException e) {
    e.printStackTrace();
    System.out.println("客户端错误");
}
}
//停止服务
public void stop() {

}

}

Request:

public class Request{
    //协议信息
    private String requestInfo;
    //请求方式
    private String method; 
    //请求url
    private String url; 
    //请求参数
    private String queryStr;
    private final  String CRLF = "\r\n";
    private Map> parameterMap;
    public Request(Socket client) throws IOException {
        this(client.getInputStream());
    }
    public Request(InputStream is) {    
        parameterMap=new HashMap>();
        byte[] datas = new byte[1024*1024];
        int len;
        try {
            len = is.read(datas);
            this.requestInfo = new String(datas,0,len);         
        } catch (IOException e) {
            e.printStackTrace();
            return ;
        }
        //分解字符串
        parseRequestInfo();
    }

private void parseRequestInfo() {
    System.out.println("------分解-------");
    System.out.println("---1、获取请求方式: 开头到第一个/------");
    this.method = this.requestInfo.substring(0, this.requestInfo.indexOf("/")).toLowerCase();
    this.method=this.method.trim();
    System.out.println("---2、获取请求url: 第一个/ 到 HTTP/------");
    System.out.println("---可能包含请求参数? 前面的为url------");
    //1)、获取/的位置
    int startIdx = this.requestInfo.indexOf("/")+1;
    //2)、获取 HTTP/的位置
    int endIdx = this.requestInfo.indexOf("HTTP/");
    //3)、分割字符串
    this.url = this.requestInfo.substring(startIdx, endIdx);        
    //4)、获取?的位置
    int queryIdx =this.url.indexOf("?");    
    if(queryIdx>=0) {//表示存在请求参数,考虑在第一个位置的情况
        String[] urlArray = this.url.split("\\?");
        this.url =urlArray[0];
        queryStr =urlArray[1];
    }
    System.out.println(this.url);

    System.out.println("---3、获取请求参数:如果Get已经获取,如果是post可能在请求体中------");

    if(method.equals("post")) {
        String qStr =this.requestInfo.substring(this.requestInfo.lastIndexOf(CRLF)).trim();
        System.out.println(qStr+"-->"); 
        if(null==queryStr) {
            queryStr =qStr;
        }else { 
            queryStr +="&"+qStr;
        }
    }
    queryStr = null==queryStr?"":queryStr;
    System.out.println(method+"-->"+url+"-->"+queryStr);
    //转成Map fav=1&fav=2&uname=shsxt&age=18&others=""
    convertMap();
}
//处理请求参数为Map
private void convertMap()
{
    //分割字符串
    String[] keyValues=this.queryStr.split("&");
    for(String queryStr:keyValues)
    {
        //再次分割字符串按=分
        String[] kv=queryStr.split("=");
        kv=Arrays.copyOf(kv, 2); //拷贝数组kv中的两个元素到kv
        //获取key和value
        String key=kv[0];
        String value=kv[1]==null?null:decode(kv[1],"utf-8");
        //存储到Map
        if(!parameterMap.containsKey(key))//如果没有,就创建
        {
            parameterMap.put(key,new ArrayList() );
        }
        parameterMap.get(key).add(value);
    }
}
//通过name获取对应的多个值
public String[] getParameterValues(String key)
{
    List values=this.parameterMap.get(key);
    if(null==values||values.size()<1)
    {
        return null;
    }
    return values.toArray(new String[0]); //将列表转成字符数组
}
//通过name获取对应的一个值
public String getParameter(String key)
{
    String[] values= getParameterValues(key);

    return values==null?null:values[0];
}
//处理中文
private String decode(String value,String enc) 
{
    try {
        return java.net.URLDecoder.decode(value,enc);//第二个参数为字符集
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }
    return null;
}
public String getMethod() {
    return method;
}

public String getUrl() {
    return url;
}

public String getQueryStr() {
    return queryStr;
}

}

Response:

public class Response {
        private BufferedWriter bw;
        //正文
        private StringBuilder content;
        //协议头(状态行与请求头 回车)信息
        private StringBuilder headInfo;
        private int len; //正文的字节数

private final String BLANK =" ";
private final  String CRLF = "\r\n";
private Response() {
        content =new StringBuilder();
        headInfo=new StringBuilder();
        len =0;
}
public Response(Socket client) {
        this();
        try {
                bw=new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
        } catch (IOException e) {
                e.printStackTrace();
                headInfo = null;
        }
}

public Response(OutputStream os) {
        this();
        bw=new BufferedWriter(new OutputStreamWriter(os));
}
//动态添加内容
public  Response print(String info) {
        content.append(info);
        len+=info.getBytes().length;
        return this;
}
public  Response println(String info) {
        content.append(info).append(CRLF);
        len+=(info+CRLF).getBytes().length;
        return this;
}

//推送响应信息
public void pushToBrowser(int code) throws IOException {
        if(null ==headInfo) {
                code = 505;
        }
        createHeadInfo(code);
        bw.append(headInfo);
        bw.append(content);
        bw.flush();
}

//构建头信息
private void createHeadInfo(int code) {
        //1、响应行: HTTP/1.1 200 OK
        headInfo.append("HTTP/1.1").append(BLANK);
        headInfo.append(code).append(BLANK);
        switch(code) {
                case 200:
                        headInfo.append("OK").append(CRLF);
                        break;
                case 404:
                        headInfo.append("NOT FOUND").append(CRLF);
                        break;  
                case 505:
                        headInfo.append("SERVER ERROR").append(CRLF);
                        break;  
        }
        //2、响应头(最后一行存在空行):
        headInfo.append("Date:").append(new Date()).append(CRLF);
        headInfo.append("Server:").append("shsxt Server/0.0.1;charset=GBK").append(CRLF);
        headInfo.append("Content-type:text/html").append(CRLF);
        headInfo.append("Content-length:").append(len).append(CRLF);
        headInfo.append(CRLF);      
}

}

分享文章:javawebserver-获取参数和处理中文
分享链接:http://scyanting.com/article/gphphp.html