我尝试使用OKHTTP Web套接字库从我的API获取数据,但无法获取数据。有人可以给我关于我所缺少的任何想法吗?构建它时没有发现错误。
运行代码时,我在设备上收到的错误应为http 101响应,但为200ok。
即使无法解决问题,任何人都可以推荐我任何其他Web套接字库来从服务器获取数据。
private TextView test;
private Button start;
private OkHttpClient client;
private static final String TAG = "WebSocketTest";
public final class WebSocketListener extends okhttp3.WebSocketListener{
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
Log.d(TAG, "Open");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
//System.out.println("MESSAGE: " + text);
Log.d(TAG, "MESSAGE: " + text);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(text);
} catch (JSONException ex) {
ex.printStackTrace();
}
if (jsonObject != null) {
try {
String lat = jsonObject.getString("latitude");
String lon = jsonObject.getString("longitude");
test.setText("Your Location is:" + lat + "--" + lon);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
output("Receiving bytes : " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
output("Error : " + t.getMessage());
}
}
private void output(final String txt) {
runOnUiThread(new Runnable() {
@Override
public void run() {
test.setText(test.getText().toString() + "\n\n" + txt);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_socket_test);
test = findViewById(R.id.txt_test);
start = findViewById(R.id.btn_start);
client = new OkHttpClient();
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
start();
}
});
}
private void start() {
Request request = new Request.Builder().url("ws://192.168.100.70:9000/location").build();
WebSocketListener listener = new WebSocketListener();
client.newWebSocket(request, listener);
client.dispatcher().executorService();
}
}