如何在Java服务器应用程序中访问HTTP PUT消息(JSON格式)? HTTP PUT是从Python客户端发送的。
到目前为止Python客户端:
import http.client
import urllib
values = {'s':'basic','submit':'search'}
data = urllib.parse.urlencode(values)
headers = headers['Content-length']=str(len(bytes(data, 'utf-8')))
connection = http.client.HTTPConnection('localhost',8080)
connection.request("PUT", "/file", body=data.encode("utf-8"))
当PUT到达Java服务器时 - 如何获取消息(来自Python的数据)?
到目前为止,这就是我在Java中所拥有的:
import java.io.*;
import java.net.*;
class JavaServer {
public static void main(String args[]) throws Exception {
String fromclient;
ServerSocket Server = new ServerSocket (8080);
System.out.println("TCPServer Waiting for client on port 8080");
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
fromclient = inFromClient.readLine();
System.out.println( "RECIEVED:" + fromclient );
}
}
答案 0 :(得分:2)
您需要迭代“inFromClient”
类似于:
while((fromclient = inFromClient.readLine()) != null){
System.out.println( "RECIEVED:" + fromclient );
}
inFromClient.close();
答案 1 :(得分:0)
谢谢。这确实有效。 我也刚刚发现了这个:
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inFromClient.readLine()) != null) {
buffer.append(line);
}
System.out.println("buffer.toString = " + buffer.toString());
然而,这也有效,json消息似乎有很多额外的字符,似乎混淆了。我是JSON的新手。也许这是正常的,或者我需要双引号。我实际上发送时间和IP地址和值。数字是否需要使用JSON进行特殊格式化?