通过Java连接到Socket服务器发送标头

时间:2015-11-18 14:23:27

标签: java sockets websocket

我希望在Java中的套接字中打开连接时发送标头。可能吗?我是否必须使用Java EE的WebSockets?

1 个答案:

答案 0 :(得分:1)

你能发贴你的代码吗? 还有你要发送的标题?你必须准确解释你想要做什么

这样的东西?

    try
    {
        Socket  s = new Socket ();
        s.bind    (new InetSocketAddress (ipFrom, 0));
        s.connect (new InetSocketAddress (ipTo,   80), 1000);

        PrintWriter     writer = new PrintWriter    (s.getOutputStream ());
        BufferedReader  reader = new BufferedReader (new InputStreamReader (s.getInputStream ()));

    writer.print ("GET " + szUrl + " HTTP/1.0\r\n"); 
//Also you can send multiple headers like this

    writer.print ("header1: value1\r\n"); 
    writer.print ("header2: value2\r\n"); 
    writer.print ("header3: value3\r\n"); 

// end the header section
writer.print ("\r\n"); 
        writer.flush ();

        s     .close ();
        reader.close ();
        writer.close ();
    }