HttpsUrlConnection returns Bad Request response

0

In an Android application, I have to connect to a web using basic authentication and https.

        HttpsURLconexion = (HttpsURLConnection) new URL(url).openConnection();
        conexion.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
        byte[] datosconexion=Base64.encode((this.nusuario + ":" + this.nclave).getBytes("UTF-8"), Base64.NO_WRAP);
        String tiraconexion=datosconexion.toString();
        conexion.setRequestProperty("\"Authorization\"", "\"Basic \"" + tiraconexion);
        conexion.setRequestProperty("\"Accept\"", "\"application/json\"");
        conexion.setConnectTimeout(10000); // 10 segundos
        conexion.setReadTimeout(10000); // 10 segundos
        conexion.setRequestMethod("GET");
        conexion.setDoOutput(true);
        conexion.setUseCaches(false);
        conexion.connect();
        respuesta = String.valueOf(conexion.getResponseCode());
        conexion.disconnect();

It always returns the code 400 (Bad Request). Any ideas?. Thank you and greetings.

    
asked by Anllares 21.11.2018 в 19:10
source

2 answers

0

Using this has worked for me:

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(nusuario,nclave.toCharArray());
            }
        });
        HttpsURLConnection conexion = null;
        conexion = (HttpsURLConnection) new URL(url).openConnection();
        conexion.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
        conexion.setConnectTimeout(10000); // 10 segundos
        conexion.setReadTimeout(10000); // 10 segundos
        conexion.setRequestProperty("Accept", "application/json");
        conexion.setRequestProperty("User-Agent","Mozilla/5.0");
        conexion.setRequestProperty("Content-Type", "application/json; charset=ISO-8859-1");
        conexion.setRequestProperty("Content-length", "0");
        conexion.setAllowUserInteraction(false);
        conexion.setRequestMethod("GET");
        conexion.setUseCaches(false);
        conexion.connect();

In case it helps someone. Greetings.

    
answered by 22.11.2018 в 12:16
-1

You should write your request like this:

    conexion.setRequestProperty("Authorization", "Basic" + tiraconexion);
    conexion.setRequestProperty("Accept", "application/json");
    
answered by 21.11.2018 в 20:17