使用Postman通过Socket传递JSON时如何解决错误

时间:2019-03-24 02:16:38

标签: java json sockets

我的团队正在尝试构建检测对象运动的应用程序,并将那些信息(JSON)发送到服务器(使用java后端)。我试图通过套接字获取JSON数据,但它显示了这种错误。我正在使用邮递员发送JSON进行测试。另一个问题是在这种情况下,使用tomcat从浏览器获取和发布数据要比使用套接字更好?

public class ThreadedEchoServer {

    static final int PORT = 5000;

    public static void main(String args[]) {
        ServerSocket serverSocket = null;
        Socket socket = null;

        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();

        }
        while (true) {
            try {
                socket = serverSocket.accept();
                System.out.println("Client connect...");
            } catch (IOException e) {
                System.out.println("I/O error: " + e);
            }
            // new thread for a client
            new EchoThread(socket).start();
        }
    }
}
public class EchoThread extends Thread {

    protected Socket socket;

    public EchoThread(Socket clientSocket) {
        this.socket = clientSocket;
    }

    public void run() {
        InputStream inp = null;
        BufferedReader brinp = null;
        PrintWriter out = null;
        try {
            inp = socket.getInputStream();
            brinp = new BufferedReader(new InputStreamReader(inp));
//            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            return;
        }
        String line;

        while (true) {
            try {
                line = brinp.readLine();
                if ((line == null) || line.equalsIgnoreCase("QUIT")) {
                    socket.close();
                    return;
                } else {
                    JSONObject json = new JSONObject(line);
                    System.out.println("Client: " + json.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }
}

这是我用邮递员发布请求的json

{
    "id": 963,
    "result": "United States",
    "cook": 30
}

但是我遇到了这个错误

Client connect...
Exception in thread "Thread-0" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
    at org.json.JSONObject.<init>(JSONObject.java:215)
    at org.json.JSONObject.<init>(JSONObject.java:399)
    at EchoThread.run(EchoThread.java:34)

0 个答案:

没有答案