如何通过Java在Web代理中实现HTTP POST方法

时间:2018-02-20 00:58:52

标签: java http network-programming http-post http-proxy

我正在尝试为服务器和客户端之间的HTTP通信创建一个Web代理。 GET方法工作正常,但我是POST方法部分无法正常工作。我相信我错过了一些东西。我想知道我错过了什么或没有实现。

// request from client is handle from here
        while ((inputLine = in.readLine()) != null) {
            try {

                StringTokenizer tok = new StringTokenizer(inputLine);
                tok.nextToken();

            } catch (Exception e) {
                break;
            }

            if (cnt == 0) {
                 System.out.println("inputLine "+inputLine);
                String[] tokens = inputLine.split(" ");
                urlToCall = tokens[1];
                //hum inputline sy URL nikaal rahay hai
                if(tokens[0]=="POST")
                {
                    f=1;
                }

                System.out.println("Request for : " + urlToCall);
            }

            cnt++;
        }

        BufferedReader rd = null;
        try {
            //yaha sy hum ab server ko request send karay gy
            URL url = new URL(urlToCall);
            URLConnection conn = url.openConnection();
            HttpURLConnection huc = (HttpURLConnection) conn;
            conn.setDoInput(true);

            conn.setDoOutput(false);

            // now we will get the response from the server

            if (f == 1) {
                huc.setDoOutput(true);
                huc.setInstanceFollowRedirects(false);
                huc.setRequestMethod("POST");
                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                huc.setRequestProperty("charset", "utf-8");
            }

            InputStream is = null;
            if (conn.getContentLength() > 0)
            {
                try {
                    is = conn.getInputStream();
                    rd = new BufferedReader(new InputStreamReader(is));
                } catch (IOException ioe) {
                    System.out.println(
                            "********* IO EXCEPTION **********: " + ioe);
                }
            }

1 个答案:

答案 0 :(得分:0)

您在帖子上遇到的错误是什么?什么是传递到代码中的示例GET请求?

当我使用简单的GET请求时,代码失败,因为urlToCall没有主机或协议。下面的代码对我有用,但我强烈建议你更改代码,不要隐藏被抛出的异常,因为它们会有关于代码出错的重要信息。

if (cnt == 1) {
            System.out.println("host: " + inputLine);
            String[] tokens = inputLine.split(" ");
            urlToCall = "HTTP://" + tokens[1] + urlToCall;
        }