-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathJSONEchoClient.java
49 lines (40 loc) · 1.78 KB
/
JSONEchoClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.doing.more.java.example;
import org.quickconnectfamily.json.JSONInputStream;
import org.quickconnectfamily.json.JSONOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Scanner;
public class JSONEchoClient {
public static void main(String[] args){
JSONEchoClient theClient = new JSONEchoClient();
theClient.go();
}
private void go() {
while(true){
try {
Scanner systemInScanner = new Scanner(System.in);
System.out.printf("Enter the message to send to the server.\n");
String messageForServer = systemInScanner.nextLine();
URL url = new URL("http://localhost:8080/json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);//allows POST
JSONOutputStream outToServer = new JSONOutputStream(connection.getOutputStream());
HashMap<String, Object> request = new HashMap<>();
request.put("command", "Speak");
request.put("message", messageForServer);
outToServer.writeObject(request);
JSONInputStream inFromServer = new JSONInputStream(connection.getInputStream());
HashMap<String, Object> response = (HashMap<String, Object>) inFromServer.readObject();
if (response.get("command").equals("Done")) {
System.out.println("Sent request: " + request + "and got response " + response);
} else {
System.out.println("Oops. got " + response);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
}