java - 无法在 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");
}
}
}
如何在 Postman 中获得回复。
解决方案
你有几件事要纠正。
首先,您将覆盖您的响应字符串
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");
推荐阅读
- r - 结合堆叠和分组图表ggplot2
- java - 如何使用 2 个不同的过滤器输入过滤相同的列表 2 次。(按 SearchView 和标签过滤)
- android - 无法解析项目:RNAdMob
- javascript - 克隆时将数据记录到适当的 html 子元素
- python-3.x - 如何在跟踪每个字符的分数的同时对字符串进行操作?
- html - 如何阻止谷歌抓取我的页面,但仍然让百度去做?
- laravel - 如何使用 bootstrap-vue
- testing - testNG 中的测试套件结果依赖性
- c# - 如何解决这个问题我的以下代码不起作用
- javascript - 返回输入数组的最大元素的函数