Java:使用TCP套接字的简单http GET请求 [英] Java: Simple http GET request using TCP sockets

查看:185
本文介绍了Java:使用TCP套接字的简单http GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本地托管一个简单的PHP echo服务器。
我试图用Java向服务器发送消息,并使用GET请求打印响应但是收到'格式错误的HTTP请求'错误。谁能告诉我如何正确格式化GET请求?

I am hosting a simple PHP echo server locally. 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. Can anyone tell me how to correctly format the GET request?

//客户代码:

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
      }
?>


推荐答案

http服务器理解GET,POST,PUT等字样,删除。所以这是一个问题:

An http server understand words like GET, POST, PUT, DELETE. So here's a problem:

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

第一个语句告诉http服务器它不理解:句子。注释掉该行和您的请求是否有效,您将收到回复。

The first statement there is telling something to the http server that it doesn't understand: the sentence. Comment out that line and your request becomes valid, and you will get a response.

我想您要将该句子作为参数发布到echo服务。你可以把它放在查询字符串中:

I guess you want to post the sentence as a parameter to the echo service. You can put it in the query string:

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

我还更改了HTTP版本并附加了额外的\ n,正如Steffen的评论所指出的那样Ullrich:

I also changed the HTTP version and appended an extra \n as pointed out by the comment of Steffen Ullrich:


此外,您必须添加空行以标记标题的结尾。并且行结尾必须是\\ n而不是\ n。你应该更好地做HTTP / 1.0请求而不是HTTP / 1.1,因为你的代码既不能处理HTTP keep-alive也不能处理HTTP chunked编码

Also you must add empty line to mark the end of the header. And the line ending must be \r\n not \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

然而,这还不够。您还需要编码一些字符,例如空格。必须对get请求中的URL进行编码,如@zapl在评论中所指出的那样。

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.

我还建议首先使用简单的telnet测试你的echo服务:

I also recommend to test your echo service first using simple telnet:

telnet localhost 8000

在那里,您可以输入消息GET /echo.php?message=something并验证其是否有效。一旦找到符合预期的东西,就可以相应地更新Java代码。

There, you can type your message, "GET /echo.php?message=something" and verify it works. Once you find something that works as intended, you can update the Java code accordingly.

这篇关于Java:使用TCP套接字的简单http GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆