我正在编写一个python客户端来向java服务器发送json消息。我认为问题出在客户端。有什么建议?这就是我所拥有的。 Python客户端是第一个Java Server,第二个。
import json
import urllib.request
import urllib.parse
url = 'http://localhost:8080'
json_input = {'sender': 'jdog', 'receiver': 'pacman', 'message': 'awesome!'}
data = json.dumps(json_input)
data = data.encode('utf-8')
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = urllib.request.Request(url, data,headers=headers, method='PUT')
resp = urllib.request.urlopen(r)
print(r.info().headers)
print(r.read())
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 );
connected.close();
}}