溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java webserver-獲取參數(shù)和處理中文

發(fā)布時(shí)間:2020-07-04 00:20:54 來源:網(wǎng)絡(luò) 閱讀:309 作者:wx5d21d5e6e5ab1 欄目:編程語(yǔ)言

Server:

public class Server04 {
        private ServerSocket serverSocket ;
        public static void main(String[] args) {
                Server04 server = new Server04();
                server.start();
        }
        //啟動(dòng)服務(wù)
        public void start() {
                try {
                        serverSocket =  new ServerSocket(8888);
                         receive();
                } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("服務(wù)器啟動(dòng)失敗....");
                }
        }
        //接受連接處理
        public void receive() {
                try {
                        Socket client = serverSocket.accept();
                        System.out.println("一個(gè)客戶端建立了連接....");
                        //獲取請(qǐng)求協(xié)議

    Request request=new Request(client);

    //關(guān)注了內(nèi)容
    Response response=new Response(client); //創(chuàng)建好了輸出流
    response.print("<html>");    //通過輸出流輸出
    response.print("<head>");
    response.print("<title>");
    response.print("服務(wù)器響應(yīng)成功");
    response.print("</title>");
    response.print("</head>");
    response.print("<body>");
    response.print("shsxt server終于回來了。。。。"+request.getParameter("uname"));
    response.print("</body>");
    response.print("</html>");
    //關(guān)注了狀態(tài)碼
    response.pushToBrowser(200);

} catch (IOException e) {
    e.printStackTrace();
    System.out.println("客戶端錯(cuò)誤");
}
}
//停止服務(wù)
public void stop() {

}

}

Request:

public class Request{
    //協(xié)議信息
    private String requestInfo;
    //請(qǐng)求方式
    private String method; 
    //請(qǐng)求url
    private String url; 
    //請(qǐng)求參數(shù)
    private String queryStr;
    private final  String CRLF = "\r\n";
    private Map<String,List<String>> parameterMap;
    public Request(Socket client) throws IOException {
        this(client.getInputStream());
    }
    public Request(InputStream is) {    
        parameterMap=new HashMap<String,List<String>>();
        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、獲取請(qǐng)求方式: 開頭到第一個(gè)/------");
    this.method = this.requestInfo.substring(0, this.requestInfo.indexOf("/")).toLowerCase();
    this.method=this.method.trim();
    System.out.println("---2、獲取請(qǐng)求url: 第一個(gè)/ 到 HTTP/------");
    System.out.println("---可能包含請(qǐng)求參數(shù)? 前面的為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) {//表示存在請(qǐng)求參數(shù),考慮在第一個(gè)位置的情況
        String[] urlArray = this.url.split("\\?");
        this.url =urlArray[0];
        queryStr =urlArray[1];
    }
    System.out.println(this.url);

    System.out.println("---3、獲取請(qǐng)求參數(shù):如果Get已經(jīng)獲取,如果是post可能在請(qǐng)求體中------");

    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);
    //轉(zhuǎn)成Map fav=1&fav=2&uname=shsxt&age=18&others=""
    convertMap();
}
//處理請(qǐng)求參數(shù)為Map
private void convertMap()
{
    //分割字符串
    String[] keyValues=this.queryStr.split("&");
    for(String queryStr:keyValues)
    {
        //再次分割字符串按=分
        String[] kv=queryStr.split("=");
        kv=Arrays.copyOf(kv, 2); //拷貝數(shù)組kv中的兩個(gè)元素到kv
        //獲取key和value
        String key=kv[0];
        String value=kv[1]==null?null:decode(kv[1],"utf-8");
        //存儲(chǔ)到Map
        if(!parameterMap.containsKey(key))//如果沒有,就創(chuàng)建
        {
            parameterMap.put(key,new ArrayList<String>() );
        }
        parameterMap.get(key).add(value);
    }
}
//通過name獲取對(duì)應(yīng)的多個(gè)值
public String[] getParameterValues(String key)
{
    List<String> values=this.parameterMap.get(key);
    if(null==values||values.size()<1)
    {
        return null;
    }
    return values.toArray(new String[0]); //將列表轉(zhuǎn)成字符數(shù)組
}
//通過name獲取對(duì)應(yīng)的一個(gè)值
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);//第二個(gè)參數(shù)為字符集
    } 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;
        //協(xié)議頭(狀態(tài)行與請(qǐng)求頭 回車)信息
        private StringBuilder headInfo;
        private int len; //正文的字節(jié)數(shù)

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));
}
//動(dòng)態(tài)添加內(nèi)容
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;
}

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

//構(gòu)建頭信息
private void createHeadInfo(int code) {
        //1、響應(yīng)行: 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、響應(yīng)頭(最后一行存在空行):
        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);      
}

}
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI