简体   繁体   English

Java:使用TCP套接字的简单http GET请求

[英]Java: Simple http GET request using TCP sockets

I am hosting a simple PHP echo server locally. 我在本地托管一个简单的PHP echo服务器。 I am trying to send a message to the server in Java, and use a GET request to print the response but am getting a 'malformed HTTP request' error. 我试图用Java向服务器发送消息,并使用GET请求打印响应,但是收到“格式错误的HTTP请求”错误。 Can anyone tell me how to correctly format the GET request? 谁能告诉我如何正确格式化GET请求?

//Client code: //客户代码:

import java.io.*;
import java.net.*;

public class TCPclient {

    public static void main(String argv[]) throws Exception {
    String sentence, modifiedSentence;
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    Socket clientSocket = new Socket("localhost", 8000);  
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            sentence = inFromUser.readLine();

            outToServer.writeBytes(sentence + "\n");
            outToServer.writeChars("GET /echo.php HTTP/1.1" +"\n"); 


            modifiedSentence = inFromServer.readLine();
            System.out.println("FROM SERVER: " + modifiedSentence);
            inFromServer.close();
            outToServer.close();
            inFromUser.close();
            clientSocket.close();
            }

}

//PHP Server code:

<?php

/* Simple php echo page 
*/

//      ini_set('display_errors', 'On');
//      error_reporting(E_ALL | E_STRICT);
      if(isset($_GET['source'])) {
        if ($_GET['source'] == "raw")
           echo file_get_contents(basename($_SERVER['PHP_SELF']));
        else
           echo "<pre>" . htmlspecialchars(file_get_contents(basename($_SERVER['PHP_SELF']))) . "</pre>";
      } else if (isset($_GET['message'])){
        echo strtoupper( htmlspecialchars($_GET['message'])) . '\n';
      } else {
?>
      <html>
        <head>
          <title>Error: No input message</title>
        </head>
        <body>
          <h1> No message</h1>
          <p>Echo server called without sending parameter</p>
        </body>
      </html>
<?php
      }
?>

An http server understand words like GET, POST, PUT, DELETE. http服务器理解GET,POST,PUT,DELETE等字样。 So here's a problem: 所以这是一个问题:

        outToServer.writeBytes(sentence + "\n");
        outToServer.writeChars("GET /echo.php HTTP/1.1" +"\n"); 

The first statement there is telling something to the http server that it doesn't understand: the sentence. 第一个声明告诉http服务器它不理解:句子。 Comment out that line and your request becomes valid, and you will get a response. 注释掉该行和您的请求是否有效,您将得到回复。

I guess you want to post the sentence as a parameter to the echo service. 我想你想把句子作为参数发布到echo服务。 You can put it in the query string: 您可以将它放在查询字符串中:

        outToServer.writeChars("GET /echo.php?message=" + sentence + " HTTP/1.0\n\n"); 

I also changed the HTTP version and appended an extra \\n as pointed out by the comment of Steffen Ullrich: 我还更改了HTTP版本并附加了一个额外的\\ n,正如Steffen Ullrich的评论所指出的那样:

Also you must add empty line to mark the end of the header. 此外,您必须添加空行以标记标题的末尾。 And the line ending must be \\r\\n not \\n. 行结尾必须是\\ r \\ n而不是\\ n。 And you should better do a HTTP/1.0 request not HTTP/1.1 since your code is neither able to deal with HTTP keep-alive nor with HTTP chunked encoding 你应该更好地做HTTP / 1.0请求而不是HTTP / 1.1因为你的代码既不能处理HTTP keep-alive也不能处理HTTP chunked编码

However, this is not quite enough. 但是,这还不够。 You also need to encode some characters, such as spaces. 您还需要对某些字符进行编码,例如空格。 The URL in the get request must be encoded, as pointed out by @zapl in a comment. 必须对get请求中的URL进行编码,如@zapl在注释中所指出的那样。

I also recommend to test your echo service first using simple telnet: 我还建议首先使用简单的telnet测试你的echo服务:

telnet localhost 8000

There, you can type your message, "GET /echo.php?message=something" and verify it works. 在那里,您可以输入您的消息,“GET /echo.php?message=something”并验证它是否有效。 Once you find something that works as intended, you can update the Java code accordingly. 一旦找到按预期工作的内容,就可以相应地更新Java代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM