JAVA HTTPClient

Тестовый класс, прошу не пинать, так сказать заготовка HelloWorld

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;



public class Http3 {

    private static final String KEYSTOREPATH = "keystore.jks"; // or .p12
    private static final String TRUSTSTOREPATH = "truststore.jks"; // or .p12
    private static final String KEYSTOREPASS = "123123";
    private static final String KEYPASS = "123123";

    KeyStore readStore() throws Exception {
        try (FileInputStream trustKeyStoreFile = new FileInputStream(new File(KEYSTOREPATH))) {
            KeyStore keyStore = KeyStore.getInstance("JKS"); // or "PKCS12"
            keyStore.load(trustKeyStoreFile, KEYSTOREPASS.toCharArray());
            return keyStore;
        }

    }

    KeyStore readTrust() throws Exception {
        try (FileInputStream trustStoreStream2 = new FileInputStream(new File(TRUSTSTOREPATH))) {
            KeyStore trustStore = KeyStore.getInstance("JKS"); // or "PKCS12"
            trustStore.load(trustStoreStream2,KEYSTOREPASS.toCharArray());
            return trustStore;
        }
    }




    public void query() throws Exception {

        System.out.println(System.getProperty("user.dir"));
        System.out.println(KEYSTOREPATH);

        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(readTrust(),null)
                //.loadTrustMaterial(null, new TrustSelfSignedStrategy())
                //.loadTrustMaterial(null, (x509CertChain, authType) -> true) //вариант принимающий всё
                .loadKeyMaterial(readStore(), KEYPASS.toCharArray()) // use null as second param if you don't have a separate key password
                .build();


        HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();

        HttpPost query = new HttpPost("https://192.168.200.10/index.php?koko=1");
        query.setHeader("р1","yes"); //заголовок
        query.setEntity(new StringEntity("ratatatat")); //тело


        HttpResponse response = httpClient.execute(query);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
        EntityUtils.consume(entity);
    }
}
Показать комментарии