如何从Java

时间:2017-11-23 00:20:59

标签: java http-proxy

如何从POST请求中提取表单数据,例如。 $ curl -X POST -d asdf = blah http://localhost:8000/proxy/http://httpbin.org/post - 我需要提取asdf = blah。

我目前正在这样做的方式在很大程度上依赖于我读过的某种格式的数据(我假设表单数据总是在最后一行)。是否有更好(和/或更简单)的方法来获取不依赖于正在读取的数据格式的数据?

(注意:代理处理GET和POST请求)

这是我写的代码:

public class ProxyThread3 extends Thread {
private Socket clientSocket = null;

private OutputStream clientOutputStream;


private static final int BUFFER_SIZE = 32768;

public ProxyThread3(Socket socket) {
    super("ProxyThread");
    this.clientSocket = socket;

}


public void run() {
    try {

        clientOutputStream = clientSocket.getOutputStream();

        // Read request
        InputStream clientInputStream = clientSocket.getInputStream();

        byte[] b = new byte[8196];
        int len = clientInputStream.read(b);

        String urlToCall = "";


        if (len > 0) {

            String userData = new String(b, 0, len);

            String[] userDataArray = userData.split("\n");

            //Parse first line to get URL
            String firstLine = userDataArray[0];
            for (int i = 0; i < firstLine.length(); i++) {

                if (firstLine.substring(i).startsWith("http://")) {

                    urlToCall = firstLine.substring(i).split(" ")[0];
                    break;
                }

            }


            //get request type
            String requestType = firstLine.split(" ")[0];

            String userAgentHeader = "";


            //get USER-AGENT Header and Accept Header
            for (String data : userDataArray) {

                if (data.startsWith("User-Agent")) {

                    userAgentHeader = data.split(":")[1].trim();
                    break;

                }

            }


            switch (requestType) {

                case "GET": {

                    sendGetRequest(urlToCall, userAgentHeader);
                    break;
                }

                case "POST": {


                    String postParams = null;

                    //Get Form Data
                    if (!userDataArray[userDataArray.length - 1].isEmpty()) {

                        postParams = userDataArray[userDataArray.length - 1];

                    }

                    sendPostRequest(urlToCall, userAgentHeader, postParams);
                    break;
                }


            }

        } else {
            clientInputStream.close();
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


private void sendPostRequest(String urlToCall, String userAgentHeader,  String postParams) throws IOException {


    URL urlToWriteAndReadFrom = new URL(urlToCall);

    HttpURLConnection httpURLConnection = (HttpURLConnection) urlToWriteAndReadFrom.openConnection();

    httpURLConnection.setRequestMethod("POST");

    // set User-Agent header
    httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);


    httpURLConnection.setDoOutput(true);

    OutputStream urlOutputStream = httpURLConnection.getOutputStream();

    if (postParams != null) {
        urlOutputStream.write(postParams.getBytes());
        urlOutputStream.flush();

    }


    urlOutputStream.close();

    int responseCode = httpURLConnection.getResponseCode();


    if (responseCode == HttpURLConnection.HTTP_OK) { // success


        InputStream dataReader = httpURLConnection.getInputStream();


        //begin send response to client
        byte inputInBytes[] = new byte[BUFFER_SIZE];

        assert dataReader != null;

        int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);

        while (index != -1) {
            clientOutputStream.write(inputInBytes, 0, index);
            index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
        }
        clientOutputStream.flush();


    }


}

private void sendGetRequest(String urlToCall, String userAgentHeader) throws IOException {


    URL urlToReadFrom = new URL(urlToCall);
    HttpURLConnection httpURLConnection = (HttpURLConnection) urlToReadFrom.openConnection();

    // set True since reading and getting input
    httpURLConnection.setDoInput(true);
    httpURLConnection.setRequestMethod("GET");

    // set User-Agent header
    httpURLConnection.setRequestProperty("User-Agent", userAgentHeader);

    int responseCode = httpURLConnection.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) { // success


        InputStream dataReader = httpURLConnection.getInputStream();


        //begin send response to client
        byte inputInBytes[] = new byte[BUFFER_SIZE];

        assert dataReader != null;

        int index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);

        while (index != -1) {
            clientOutputStream.write(inputInBytes, 0, index);
            index = dataReader.read(inputInBytes, 0, BUFFER_SIZE);
        }
        clientOutputStream.flush();


    }


}

}

PS。我是所有这一切的新手,所以如果我的代码中有任何错误,请指出它们

1 个答案:

答案 0 :(得分:0)

以下是有关如何创建处理POST和GET请求的Java HTTP服务器的完整示例。

https://www.codeproject.com/Tips/1040097/Create-a-Simple-Web-Server-in-Java-HTTP-Server

这是共享的,这是非常原始的,我建议使用任何第三方库或轻量级Java服务器,如GrizzlyJetty,如果不是像Apache Tomcat这样的服务器利用J2EE Servlets为此目的。