HttpServer

import java.util.HashMap;
import java.util.Map;

public class Request {
    // 璇锋眰鏂规硶
    private String method;
    // 璇锋眰璺緞
    private String url;
    // http鐗堟湰鍙?
    private String version;
    // 璇锋眰澶?
    private Map<String, String> headers = new HashMap<>();
    // 璇锋眰鍙傛暟
    private Map<String, String> parameters = new HashMap<>();
    // 娣诲姞璇锋眰澶?
    public void addHeader(String key, String value){
        headers.put(key, value);
    }
    // 鑾峰彇鏌愪釜璇锋眰澶?
    public String getHeader(String key){
        return headers.get(key);
    }
    // 瑙f瀽璇锋眰鍙傛暟key1=value1&key2=value2
    public void parseParameters(String parameters){
        String[] ps = parameters.split("&");
        for(String p : ps){
            String[] array = p.split("=");
            addParameter(array[0], array[1]);
        }
    }
    // 娣诲姞璇锋眰鍙傛暟
    public void addParameter(String key, String value){
        parameters.put(key, value);
    }
    // 鑾峰彇璇锋眰鍙傛暟
    public String getParameter(String key){
        return parameters.get(key);
    }

    @Override
    public String toString() {
        return "Request{" +
                "\n method='" + method + '\'' +
                ",\n url='" + url + '\'' +
                ",\n version='" + version + '\'' +
                ",\n headers=" + headers +
                ",\n parameters=" + parameters +
                '}';
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public Map<String, String> getParameters() {
        return parameters;
    }

    public void setParameters(Map<String, String> parameters) {
        this.parameters = parameters;
    }
}

Request 此代码为请求http的服务 下接一个httpsever.java
文件来进行回应

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServer {

    private static final int PORT = 9999;
    // 鑾峰彇澶勭悊鍣ㄦ牳鏁?
    private static final int COUNT = Runtime.getRuntime()
            .availableProcessors();
    // 澶勭悊鐨勪换鍔¢噺鍜岀嚎绋嬫暟閲忋€丆PU銆佸唴瀛樼瓑璧勬簮閮界浉鍏筹紝
    // 涓€鑸帹鑽愬鐞嗗櫒鏍告暟鏁伴噺鐨勭嚎绋?
    private static final ExecutorService EXE
            = Executors.newFixedThreadPool(COUNT);

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(PORT);
        while(true) {
            // 鑾峰彇瀹㈡埛绔姹俿ocket瀵硅薄锛氶樆濉炴柟娉?
            Socket socket = server.accept();
            EXE.submit(new HttpTask(socket));
        }
    }
}
// Http璇锋眰浠诲姟澶勭悊绫?
class HttpTask implements Runnable{

    private Socket socket;

    public HttpTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //鑾峰彇瀹㈡埛绔姹傛暟鎹細杈撳叆娴?
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        //鑾峰彇瀹㈡埛绔緭鍑烘祦锛岃繑鍥炲搷搴旀暟鎹?
        OutputStream os = null;
        PrintWriter pw = null;
        try {
            try {
                is = socket.getInputStream();
                isr = new InputStreamReader
                        (is, "UTF-8");
                br = new BufferedReader(isr);
                Request request = new Request();
                // 璇锋眰鏁版嵁鐨勮В鏋愶細http鍗忚鎶ョ殑瑙e寘
                // 1.瑙f瀽璇锋眰琛岋紙绗竴琛岋級锛歮ethod url version
                String requestLine = br.readLine();
                String[] requestLines = requestLine.split(" ");
                request.setMethod(requestLines[0]);
                //鍙兘涓篽ttp://localhost:9999/xxx?username=stu&password=123
                String url = requestLines[1];
                if(url.contains("?")){
                    String parameters = url.substring(url.indexOf("?")+1);
                    request.parseParameters(parameters);
                    url = url.substring(0, url.indexOf("?"));
                }
                request.setUrl(url);
                request.setVersion(requestLines[2]);
                // 2.瑙f瀽璇锋眰澶达細
                // key:value姣忎釜鎹㈣锛屼互绌鸿浣滀负缁撳熬
                String header;
                while((header=br.readLine())!=null
                        && header.length()!=0){//split鎴栨槸substring鑾峰彇
                    String key = header.substring(0, header.indexOf(":"));
                    String value = header.substring(header.indexOf(":")+1);
                    request.addHeader(key, value.trim());
                }
                // POST璇锋眰锛岄渶瑕佹牴鎹姹傚ごContent-Length鑾峰彇璇锋眰浣撶殑闀垮害
                if("POST".equals(request.getMethod())){
                    String len = request.getHeader("Content-Length");
                    if(len!=null){
                        int l = Integer.parseInt(len);
                        char[] chars = new char[l];
                        br.read(chars, 0, l);
                        //璇锋眰鍙傛暟鏍煎紡锛歶sername=stu&password=123
                        String requestBody = new String(chars);
                        request.parseParameters(requestBody);
                    }
                }
                System.out.println(request);

                os = socket.getOutputStream();
                pw = new PrintWriter(os, true);

                if("/302".equals(request.getUrl())){
                    pw.println("HTTP/1.1 302 閲嶅畾鍚?);
                    pw.println("Content-Type: text/html;charset=utf-8");
                    pw.println("Location: https://www.baidu.com");
                }
            } finally {
                if (br != null)
                    br.close();
                if (isr != null)
                    isr.close();
                if (is != null)
                    is.close();
                if(pw != null)
                    pw.close();
                if(os != null)
                    os.close();
                socket.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值