如何在Java中使用套接字发送JSON响应 [英] How to send JSON response using socket in Java

查看:126
本文介绍了如何在Java中使用套接字发送JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个基本的HTTP服务器,并且正在尝试向GET请求发送回复。我已经安装了Gson作为JSON解析器,但我不确定如何将响应编码为JSON并发送回客户端。



这是我的代码,任何非常感谢帮助。 (实际响应的最后一种方法)

pre $ public class HttpServer extends Thread {

// Private variables
私人Socket connectedClient = null;
private BufferedReader clientRequest = null;
private DataOutputStream responseToClient = null;
$ b / **
*公共构造函数
* @param客户端
* /
公共HttpServer(套接字客户端){
connectedClient = client ;

$ b $ **
*在线程上执行的代码
* /
public void run(){

尝试{

//记录新客户端
System.out.println(客户端+ connectedClient.getInetAddress()+
:+ connectedClient.getPort()+ 已连接);

//获取客户端请求
clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

//启动响应对象
responseToClient = new DataOutputStream(connectedClient.getOutputStream());

//处理请求
processClientRequest();

//关闭缓冲写入器
responseToClient.close();
} catch(Exception e){

//打印错误
e.printStackTrace();


$ b $ **
*解析一个客户端请求并调用approriate处理程序
* @throws异常
* /
private void processClientRequest()抛出异常{

字符串requestString = clientRequest.readLine();

String header = requestString;

//分解请求
StringTokenizer tokenizer = new StringTokenizer(header);

//不同的请求部分
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();

//打印客户端请求
StringBuffer responseBuffer = new StringBuffer();
while(clientRequest.ready()){
responseBuffer.append(requestString +);
System.out.println(requestString);

requestString = clientRequest.readLine();
}
// ID GET请求
if(requestString.equals(GET)){
if(httpQueryString.equals(/)){
sendResponse();




$ **
*回复客户
* @throws异常
* /
private void sendResponse()抛出异常{

HashMap< String,String> mapResponse = new HashMap< String,String>();
mapResponse.put(A,Hands);
mapResponse.put(B,Feet);

//转换为JSON并发送回客户端
// ????????????????????????????? ???
}
}


解决方案

您查看了GSON的用户指南?我怀疑你想要的东西符合

  Gson gson = new Gson(); 
String json = gson.toJson(mapResponse);

要将数据写回套接字,请看读取和写入套接字。这可能会起作用:

$ p $ new PrintWriter(responseToClient,true).println(json);


I have built a basic HTTP server and I am attempting to send a reply to a GET request. I have installed Gson as the JSON parser, but I'm not sure how to encode the response in JSON and send back to the client.

Here is my code, any help is much appreciated. (last method for actual response)

public class HttpServer extends Thread{

    //Private variables
    private Socket connectedClient = null;
    private BufferedReader clientRequest = null;
    private DataOutputStream responseToClient = null;

    /**
     * Public constructor
     * @param client
     */
    public HttpServer(Socket client){
        connectedClient =client;
    }

    /**
     * Code to execute on thread
     */
    public void run(){

        try {

            //Log new client
            System.out.println("The client " + connectedClient.getInetAddress() + 
                    ":" + connectedClient.getPort() + " is connected");

            //Get the client request
            clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

            //Start response object
            responseToClient = new DataOutputStream(connectedClient.getOutputStream());

            //Process the request
            processClientRequest();

            //Close buffered writer
            responseToClient.close();
        } catch (Exception e) {

            //Print error
            e.printStackTrace();
        }
    }

    /**
     * Parses a client request and calls the approriate handler
     * @throws Exception
     */
    private void processClientRequest() throws Exception{

        String requestString = clientRequest.readLine();

        String header = requestString;

        //Break up request
        StringTokenizer tokenizer = new StringTokenizer(header);

        //Different request parts
        String httpMethod = tokenizer.nextToken();
        String httpQueryString = tokenizer.nextToken();

        //Print client request
        StringBuffer responseBuffer = new StringBuffer();
        while (clientRequest.ready()) {
            responseBuffer.append(requestString + " ");
            System.out.println(requestString);

            requestString = clientRequest.readLine();
        }
        //ID GET request
        if (requestString.equals("GET")) {
            if (httpQueryString.equals("/")) {
                sendResponse();

            }   
        }
    }

    /**
     * Sends reply back to client
     * @throws Exception
     */
    private void sendResponse() throws Exception{

        HashMap<String, String> mapResponse = new HashMap<String, String>();
        mapResponse.put("A", "Hands");
        mapResponse.put("B", "Feet");

        //Convert to JSON and send back to client
        //?????????????????????????????
    }
}

解决方案

Have you looked at the user guide for GSON? I suspect you want something along the lines of

Gson gson = new Gson();
String json = gson.toJson(mapResponse); 

To write data back to the socket look at Reading from and Writing to a Socket. This might work:

new PrintWriter(responseToClient, true).println(json);

这篇关于如何在Java中使用套接字发送JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆