首页 > 解决方案 > 无法在 Postman 中获得 HTTP 调用的响应

问题描述

我在 java 中的套接字上收到 HTTP 调用。我正在从邮递员发送 HTTP 中的小数据,并且能够在我的 java 应用程序中接收它,但是邮递员没有收到 Java 发送的响应。

这是我的 Java 结束代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;




public class MainClass {

    public static void main(String args[]) {

        ServerSocket scket;
        Socket clientSocket;
        byte inFromInde[] = new byte[1000];
        int read_size_inde = 0;


        try{
            scket = new ServerSocket(7502);
            scket.setReuseAddress(true);
            clientSocket = scket.accept();
            System.out.println("Connection accepted");

            BufferedInputStream inputFromInde = new BufferedInputStream(clientSocket.getInputStream());
            read_size_inde = inputFromInde.read(inFromInde,0,1000);
            String str = new String(inFromInde);
            System.out.println(str);
            BufferedOutputStream outputToInde = new BufferedOutputStream(clientSocket.getOutputStream());
            OutputStream output = clientSocket.getOutputStream();


           String response = "HTTP/1.1 200 OK\r\n";
           response = response = "Date: Fri, 04 May 2001 20:08:11 GMT\r\n";
           response = response + "Server: Sanjits Server\r\n";
           response = response + "Connection: close\r\n";
           response = "Hi Hope you are doing good";
           byte[] bytes = response.getBytes();
           output.write(bytes);
           output.flush();
           output.close();
           scket.close();
           clientSocket.close();

        }
        catch(Exception e){

            System.out.println("Exception is bind Failed");

        }
    }

}

Eclipse 中的控制台输出

邮递员侧面图

如何在 Postman 中获得回复。

标签: javaapihttp

解决方案


你有几件事要纠正。

首先,您将覆盖您的响应字符串

response = response = "Date: Fri, 04 May 2001 20:08:11 GMT\r\n";
....
response = "Hi Hope you are doing good";

您可能想要连接您的字符串,例如

response = response + "text";

或者

response += "text";

或使用 concat 方法

response = response.concat("text");

您的其他问题与您的回复格式有关。
根据 HTTP 规范,响应中的标头和正文应由 CRLF ( https://www.rfc-editor.org/rfc/rfc2616#section-6 ) 分隔。

为了符合要求,您必须使用 CRLF 终止标头部分,因此您必须添加一个额外的\r\n (如 VGR 所说)。

所以你的响应构建应该看起来像这样

String response = "HTTP/1.1 200 OK\r\n"
    .concat("Date: Fri, 04 May 2001 20:08:11 GMT\r\n")
    .concat("Server: Sanjits Server\r\n")
    .concat("Connection: close\r\n")
    .concat("\r\n") //additional CRLF!
    .concat("Hi Hope you are doing good");

推荐阅读