以下是一个使用OkHttp进行ping测试的示例代码:

import java.io.IOException;
import java.net.InetAddress;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PingTest {

    public static void main(String[] args) {

        OkHttpClient client = new OkHttpClient();

        String host = "www.google.com";

        try {
            InetAddress address = InetAddress.getByName(host);
            String ipAddress = address.getHostAddress();

            Request request = new Request.Builder()
                    .url("http://" + ipAddress)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println("Failed to ping " + host + ": " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        System.out.println("Successfully pinged " + host);
                    } else {
                        System.out.println("Failed to ping " + host + ": " + response.code() + " " + response.message());
                    }
                }
            });
        } catch (IOException e) {
            System.out.println("Failed to resolve host " + host);
        }
    }
}

该代码使用InetAddress类获取指定主机名的IP地址,并将其用于构建一个OkHttp请求。然后,使用enqueue方法将请求异步发送到服务器,并在回调中处理响应。如果响应成功,则说明主机可以ping通;否则,说明主机无法ping通

Android okhttp怎么测试能否ping通某个http主机地址 给我看看示例代码

原文地址: https://www.cveoy.top/t/topic/fHQo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录