I am making an application to collect a series of data from several websites. In one of them to do so I must communicate with the server through a WebSocket. This WebSocket has a series of parameters in the Header:
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36
Upgrade: websocket
Sec-WebSocket-Version: 13
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,es;q=0.9,en;q=0.8,en-US;q=0.7
Sec-WebSocket-Key: k+ghkoMFCs/FZ3DkJtNKyg==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: zap-protocol-v1
I was looking for a way to implement the WebSocket in java SE and I found Jetty, after reviewing several examples in none of them I have seen that it is possible to define Header variables. There is some way to implement this task with Jetty or I should look for some other alternative
My code is the following, I tried to follow some examples that I found but the truth is that it is the first time I touch this topic and I am somewhat lost.
public class Bet365ServerRequest {
public static void main(String[] args) {
String dest = "wss://premws-pt3.365lpodds.com/zap/?uid=5072739771513135";//
WebSocketClient client = new WebSocketClient();
try {
Bet365ClientSocket socket = new Bet365ClientSocket();
client.start();
URI bet365Uri = new URI(dest);
ClientUpgradeRequest request = new ClientUpgradeRequest();
client.connect(socket, bet365Uri, request);
socket.getLatch().await();
socket.sendMessage("#?P?__time,S_280C2F9D9EF86C59847B787B7312C1FC000003");
Thread.sleep(10000l);
}catch(Throwable t) {
t.printStackTrace();
}finally {
try {
client.stop();
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
@WebSocket
public class Bet365ClientSocket{
private Session session;
CountDownLatch latch= new CountDownLatch(1);
@OnWebSocketMessage
public void onText(Session session, String message) throws IOException {
System.out.println("Message received from server:" + message);
}
@OnWebSocketConnect
public void onConnect(Session session) {
UpgradeRequest request = session.getUpgradeRequest();
//request.setH
Map<String, List<String>> params = request.getParameterMap();
List<String> language = params.get("lang");
if (language != null && language.size() > 0) {
String lang = language.get(0);
System.out.println("Connected to server");
this.session=session;
latch.countDown();
}
}
public void sendMessage(String str) {
try {
session.getRemote().sendString(str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public CountDownLatch getLatch() {
return latch;
}
}
The only message that appears on the console after executing the code is the following:
2018-11-20 19:09:55.419:INFO::main: Logging initialized @761ms to org.eclipse.jetty.util.log.StdErrLog