Java HTTP POST y GET convierten de CURL

StealthRT:

Hola a todos Estoy haciendo mi mejor esfuerzo para convertir este script CURL trabajando para Java:

@ECHO off
set COOKIES=.\cookies.txt
set USER=myUN
set PASSWORD="myPW"
set HOST=https://zzzzzzz.zzzzz.zz.zz:9443

cls

ECHO "Get the session cookie-------------------------------------"
    set out1 = curl -k -c %cookies% "%host%/qm/authenticated/identity" > nul
ECHO "-----------------------------------------------------------"

ECHO "Use the session cookie to logon----------------------------"
    curl -k -L -b %COOKIES% -c %COOKIES% -d j_username=%USER% -d j_password=%PASSWORD% %host%/qm/authenticated/j_security_check > nul
ECHO "-----------------------------------------------------------"

ECHO "Use the cookie to get the catalog--------------------------"
    curl -k -L -b %COOKIES% -H "Accept: application/xml" %host%/qm/process/project-areas/_zzzzzzzzzzzzzzzzzzzz/members
ECHO "-----------------------------------------------------------"

dónde:

               -k: Allow insecure server connections when using SSL
    -c <filename>: Write cookies to <filename> after operation
               -L: Follow redirects
        -b <data>: Send cookies from string/file
-H <header/@file>: Pass custom header(s) to server
        -d <data>: HTTP POST data

He buscado alrededor de código Java que incluye un ejemplo de cómo crear una cookie, pero todavía tengo que encontrar algo que me ayudaría con mi código de seguridad.

El más cercano que pude encontrar y modificar el POSTE llamada es la siguiente:

CookieStore cookieStore = new BasicCookieStore();
String USER     = "myUN";
String PASSWORD = "myPW";
String HOST     = "https://zzzzzzz.zzzzz.zz.zz:9443";

// CookieSpecs.STANDARD is the RFC 6265 compliant policy
RequestConfig requestConfig = RequestConfig
                              .custom()
                              .setCookieSpec(CookieSpecs.STANDARD)
                              .build();

// automatically follow redirects
CloseableHttpClient client = HttpClients
                            .custom()
                            .setRedirectStrategy(new LaxRedirectStrategy())
                            .setDefaultRequestConfig(requestConfig)
                            .setDefaultCookieStore(cookieStore)
                            .build();
HttpPost postIT                  = new HttpPost(HOST + "/qm/authenticated/identity");
List<NameValuePair> urlParams    = new ArrayList<>();

urlParams.add(new BasicNameValuePair("j_username", USER));
urlParams.add(new BasicNameValuePair("j_password", PASSWORD));
postIT.setEntity(new UrlEncodedFormEntity(urlParams));

HttpResponse mmmCookie = client.execute(postIT);
// ... we have our cookie!

Para el post-it el valor es:

POSTAL https: //zzzzz.zzz.zzzz.zzzz: 9443 / qm / autenticado / identidad HTTP / 1.1

Sin embargo, tiene un error de:

de error: null

No sé por qué el error es nulo desde el post-it tiene datos? Así que no sólo soy yo no es capaz de ejecutar el código modificado que hice, todavía me pregunto cómo hago para llamar a un GET de comandos utilizando el cookie puede incluso si el código anterior funcionó.

Así, en pocas palabras:

  • Fijar HttpPost error.
  • ¿Cómo enviar cookie en otros métodos GET.

Ayuda sería grande!

actualizar para VGR:

public static void main(String[] args) throws IOException {
    Path currentRelativePath = Paths.get("").toAbsolutePath();
    PermissiveTrustManager blah = new PermissiveTrustManager();

    blah.readMembers("https://zzzzzz.zzzz.zz.zzz:9443", "zzzzzz", "zzzzzzz", currentRelativePath);
}

El error está en esta línea:

check(tm -> tm.checkServerTrusted(certChain, authType, socket), socket);

certChain, authType y toma todas tienen datos en ellos.

VGR:

Dado que no sabemos lo que está causando el error críptico, sugeriría el abandono de la biblioteca de terceros, y utilizando el paquete java.net:

public void readMembers(String schemeAndAuthority,
                        String username,
                        String password,
                        Path membersFileToWrite)
throws IOException {

    URI baseURI = URI.create(schemeAndAuthority);

    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    boolean oldFollowRedirects = HttpURLConnection.getFollowRedirects();

    CookieHandler.setDefault(new CookieManager());
    HttpURLConnection.setFollowRedirects(true);

    try {
        HttpURLConnection connection;

        URI authURI = baseURI.resolve("/qm/authenticated/identity");
        connection = (HttpURLConnection) authURI.toURL().openConnection();
        connection.getResponseCode();

        URI securityURI = baseURI.resolve(
            "/qm/authenticated/j_security_check");
        String postData = 
            "j_username=" + URLEncoder.encode(username, "UTF-8") + "&" +
            "j_password=" + URLEncoder.encode(password, "UTF-8");
        connection = (HttpURLConnection)
            securityURI.toURL().openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        try (OutputStream postBody = connection.getOutputStream()) {
            postBody.write(postData.getBytes(StandardCharsets.UTF_8));
        }
        connection.getResponseCode();

        URI catalogURI = baseURI.resolve(
            "/qm/process/project-areas/_zzzzzzzzzzzzzzzzzzzz/members");
        connection = (HttpURLConnection)
            catalogURI.toURL().openConnection();
        connection.setRequestProperty("Accept", "application/xml");
        try (InputStream responseBody = connection.getInputStream()) {
            Files.copy(responseBody, membersFileToWrite);
        }
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
        HttpURLConnection.setFollowRedirects(oldFollowRedirects);
    }
}

Sin embargo, el código anterior no proporciona el equivalente de rizo -kopción. Por eso, tenemos que crear una costumbre SSLContext , inicializado con un TrustManager que permite que todos los certificados:

static class PermissiveTrustManager
extends X509ExtendedTrustManager {
    private final X509ExtendedTrustManager[] realTrustManagers;

    private interface Checker {
        void checkWith(X509ExtendedTrustManager realTrustManager)
        throws CertificateException;
    }

    PermissiveTrustManager() {
        TrustManagerFactory factory;
        try {
            factory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
            factory.init((KeyStore) null);
        } catch (GeneralSecurityException e) {
            // We should not be able to get here.
            throw new RuntimeException(e);
        }

        TrustManager[] allTrustManagers = factory.getTrustManagers();
        realTrustManagers = Arrays.stream(allTrustManagers)
            .filter(tm -> tm instanceof X509ExtendedTrustManager)
            .map(tm -> (X509ExtendedTrustManager) tm)
            .toArray(X509ExtendedTrustManager[]::new);

    }

    private void check(Checker checker) {
        try {
            for (X509ExtendedTrustManager realTrustManager : realTrustManagers) {
                checker.checkWith(realTrustManager);
            }
        } catch (CertificateException e) {
            System.err.println("Ignoring invalid certificate");
            e.printStackTrace();
        }
    }

    private void check(Checker checker,
                       Socket socket) {
        try {
            for (X509ExtendedTrustManager realTrustManager : realTrustManagers) {
                checker.checkWith(realTrustManager);
            }
        } catch (CertificateException e) {
            System.err.println("Ignoring invalid certificate for " + 
                socket.getRemoteSocketAddress());
            e.printStackTrace();
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] certChain,
                                   String authType,
                                   Socket socket) {
        check(tm -> tm.checkClientTrusted(certChain, authType, socket), socket);
    }

    @Override
    public void checkClientTrusted(X509Certificate[] certChain,
                                   String authType,
                                   SSLEngine engine) {
        check(tm -> tm.checkClientTrusted(certChain, authType, engine));
    }

    @Override
    public void checkServerTrusted(X509Certificate[] certChain,
                                   String authType,
                                   Socket socket) {
        check(tm -> tm.checkServerTrusted(certChain, authType, socket), socket);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] certChain,
                                   String authType,
                                   SSLEngine engine) {
        check(tm -> tm.checkServerTrusted(certChain, authType, engine));
    }

    @Override
    public void checkClientTrusted(X509Certificate[] certChain,
                                   String authType) {
        check(tm -> tm.checkClientTrusted(certChain, authType));
    }

    @Override
    public void checkServerTrusted(X509Certificate[] certChain,
                                   String authType) {
        check(tm -> tm.checkServerTrusted(certChain, authType));
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

private static SSLContext createPermissiveSSLContext()
throws IOException {

    TrustManager[] trustManagers = { new PermissiveTrustManager() };

    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);
        return context;
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

public void readMembers(String schemeAndAuthority,
                        String username,
                        String password,
                        Path membersFileToWrite)
throws IOException {

    URI baseURI = URI.create(schemeAndAuthority);

    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    boolean oldFollowRedirects = HttpURLConnection.getFollowRedirects();
    SSLContext oldSSLContext = null;
    try {
        oldSSLContext = SSLContext.getDefault();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }

    CookieHandler.setDefault(new CookieManager());
    HttpURLConnection.setFollowRedirects(true);
    SSLContext.setDefault(createPermissiveSSLContext());

    try {
        HttpURLConnection connection;

        URI authURI = baseURI.resolve("/qm/authenticated/identity");
        connection = (HttpURLConnection) authURI.toURL().openConnection();
        connection.getResponseCode();

        URI securityURI = baseURI.resolve(
            "/qm/authenticated/j_security_check");
        String postData = 
            "j_username=" + URLEncoder.encode(username, "UTF-8") + "&" +
            "j_password=" + URLEncoder.encode(password, "UTF-8");
        connection = (HttpURLConnection)
            securityURI.toURL().openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        try (OutputStream postBody = connection.getOutputStream()) {
            postBody.write(postData.getBytes(StandardCharsets.UTF_8));
        }
        connection.getResponseCode();

        URI catalogURI = baseURI.resolve(
            "/qm/process/project-areas/_zzzzzzzzzzzzzzzzzzzz/members");
        connection = (HttpURLConnection)
            catalogURI.toURL().openConnection();
        connection.setRequestProperty("Accept", "application/xml");
        try (InputStream responseBody = connection.getInputStream()) {
            Files.copy(responseBody, membersFileToWrite);
        }
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
        HttpURLConnection.setFollowRedirects(oldFollowRedirects);
        if (oldSSLContext != null) {
            SSLContext.setDefault(oldSSLContext);
        }
    }
}

Obviamente, no tengo manera de probar esto.

Se le podría llamar el método de la siguiente manera:

new CatalogRetriever().readMembers(
    "https://zzzzzzz.zzzzz.zz.zz:9443", "myUN", "myPW",
    Paths.get("members"));

Como se describe en los documentos de URI , el esquema es el http:o https:parte. La autoridad está //seguido por un nombre de host / puerto (y de usuario / contraseña opcional, dependiendo del protocolo).

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=277822&siteId=1
Recomendado
Clasificación