使用Java类作为客户端发送JSON对象

时间:2014-03-04 04:15:15

标签: java json

我已经建立了一个Java类(客户端)来连接服务器,我的要求是将JSON对象发送到服务器并获取响应。

我已经有了一个JSON对象但是我不知道如何用Java将JSON对象发送到服务器。

3 个答案:

答案 0 :(得分:0)

使用Restlet:

// Create the client resource  
ClientResource resource = new ClientResource("http://restlet.org");  

// Write the response entity on the console  
resource.post(yourJsonObject).write(System.out);  

有关详细信息,请参阅http://restlet.org/learn/tutorial/2.1/#part02

答案 1 :(得分:0)

试试这可能会有所帮助

   public boolean reset() {
        DataInputStream is;
        DataOutputStream os;
        boolean result = true;
        String noReset = "Could not reset.";
        String reset = "The server has been reset.";

        try {
            Socket socket = new Socket(InetAddress.getByName("x.x.x.x"), 3994);
            String string = "{\"id\":1,\"method\":\"object.deleteAll\",\"params\":[\"subscriber\"]}";
            is = new DataInputStream(socket.getInputStream());
            os = new DataOutputStream(socket.getOutputStream());
            PrintWriter pw = new PrintWriter(os);
            pw.println(string);
            pw.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            JSONObject json = new JSONObject(in.readLine());
            if(!json.has("result")) {
                System.out.println(noReset);
                result = false;
            }
            is.close();
            os.close();

        } catch (IOException e) {
            result = false;
            System.out.println(noReset);
            e.printStackTrace();            
        } catch (JSONException e) {
            result = false;
            System.out.println(noReset);
            e.printStackTrace();
        }
        System.out.println(reset);
        return result;
    }

答案 2 :(得分:0)

您可以使用Jackson JSON处理器将Java对象转换为JSON字符串并将其发送到服务器。

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String jsonString = ow.writeValueAsString(yourObject);

然后您可以使用HTTPClient将字符串发布到服务器:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://x.x.x.x:3994");
request.addHeader("Content-Type", "application/json");
request.setEntity(jsonString);
HttpResponse response = httpClient.execute(request);
...
httpClient.getConnectionManager().shutdown();

或者,如果您使用Sockets连接:

Socket socket = new Socket(InetAddress.getByName("x.x.x.x"), 3994);
DataInputStream is = new DataInputStream(socket.getInputStream());
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
PrintWriter pw = new PrintWriter(os);
pw.println(jsonString);
pw.flush();

BufferedReader in = new BufferedReader(new InputStreamReader(is));
JSONObject json = new JSONObject(in.readLine());
....

is.close();
os.close();