Newer
Older
CasicTimeGuard / src / main / java / com / casic / swing / utils / HttpRequestHelper.java
package com.casic.swing.utils;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author a203
 */
public class HttpRequestHelper {
    public static RequestBody createRequestBody(String value) {
        return RequestBody.Companion.create(value, MediaType.parse("application/json; charset=utf-8"));
    }

    public static void doHttpRequest(Request request, IHttpCallback httpCallback) {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                httpCallback.onFailure(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    if (response.body() != null) {
                        String string = Objects.requireNonNull(response.body()).string();
                        httpCallback.onSuccess(string);
                    } else {
                        httpCallback.onFailure(new NullPointerException());
                    }
                } catch (IOException e) {
                    httpCallback.onFailure(e);
                }
            }
        });
    }

    public static List<InetAddress> localHost() {
        List<InetAddress> addressList = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while (interfaces.hasMoreElements()) {
                NetworkInterface netInterface = interfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip instanceof Inet4Address) {
                            addressList.add(ip);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return addressList;
    }
}