套接字:简单的POST请求无法正常工作

时间:2012-07-13 05:53:23

标签: java sockets http-post

我正在尝试在此页http://www2.gcitrading.com/quotes/converter.asp上发布帖子请求, 但它不起作用..我的帖子请求后仍然得到相同的页面(没有结果)。

当我使用浏览器时,点击转换后页面转到http://www2.gcitrading.com/quotes/converter.asp?lang=我真的很困惑这个。我怎样才能做到这一点?

这是我的代码:

public static void main(String[] args) {
    Socket sock = new Socket();
    InputStream in;
    OutputStream out;
    byte[] readBuffer = new byte[4096];

    String res = "";
        try {
        sock.connect(new InetSocketAddress("www2.gcitrading.com", 80));

        in = sock.getInputStream();
        out = sock.getOutputStream();

        out.write(new String("GET /quotes/converter.asp HTTP/1.1\r\n").getBytes());
        out.write(new String("Host: www2.gcitrading.com\r\n\r\n").getBytes());

        while(true) {
            int readSize = in.read(readBuffer);
            if(readSize < 1)
                break;
            res += new String(readBuffer, 0, readSize);
            if(res.contains("</html>"))
                break;
        }

        String cookie = res.substring(res.indexOf("kie:") + 5,res.indexOf("path=/")+6);
        System.out.println("SHow cookie - " + cookie);

        String convert_this = URLEncoder.encode("form_amount=1&form_from_currency=DZD&form_to_currency=USD", "UTF-8");

        out.write(new String("POST /quotes/converter.asp?lang= HTTP/1.1\r\n").getBytes());
        out.write(new String("Host: www2.gcitrading.com\r\n").getBytes());

        out.write(new String("Content-Length: " + convert_this.length() + "\r\n").getBytes());
        out.write(new String("Content-Type: application/x-www-form-urlencoded\r\n").getBytes());
        out.write(new String("Cookie: " + cookie +"\r\n").getBytes());
        out.write(new String("\r\n").getBytes());
        out.write(convert_this.getBytes());

        readBuffer = new byte[4096];
        res = "";

        while(true) {
            int readSize = in.read(readBuffer);
            if(readSize < 1)
                break;
            res += new String(readBuffer, 0, readSize);
            if(res.contains("</html>"))
                break;
        }

        System.out.println(res);


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

感谢。顺便说一句,我需要使用c / c ++套接字实现这一点,但我先用java测试它。

3 个答案:

答案 0 :(得分:1)

我试着这是它的工作

String convert_this = URLEncoder.encode("form_amount", "UTF-8")+ "=" + URLEncoder.encode("1", "UTF-8");
convert_this += "&" + URLEncoder.encode("form_from_currency", "UTF-8")+ "=" + URLEncoder.encode("DZD", "UTF-8");
convert_this += "&" + URLEncoder.encode("form_to_currency", "UTF-8")+ "=" + URLEncoder.encode("USD", "UTF-8");

答案 1 :(得分:0)

尝试这样的事情:

DataOutputStream dataOut = new DataOutputStream(sock.getOutputStream());
dataOut.writeUTF("[Your String here]"); 

此外,您应该使用更高级别的URL,而不是套接字。

答案 2 :(得分:0)

它已经解决了。我使用了Charles,这是一个网络调试工具,发现我的帖子请求缺乏。我只是在帖子请求中添加了convert_it=true