Error creating connection with PHP

0

When creating the connection activity in the connection.getRequestMethod ("POST") field; does not accept the Post method.

I'm new to the area, could you help me?

public static String postdados(String urlusuario, String parametrousuario) {

    URL url;
    HttpURLConnection connection = null;

    try{

        url = new URL (urlusuario);
        connection = (HttpURLConnection) url.openConnection();

        connection.getRequestMethod("POST");

        connection.setRequestProperty( "content-type", "application/x-www-form-urlencoded" );

        connection.setRequestProperty( "content-lenght", "" + Integer.toString( parametrousuario.getBytes().length ) );

        connection.setRequestProperty( "content-language", "pt-BR");

        connection.setUseCaches( false );
        connection.setDoInput( true );
        connection.setDoOutput( true );

        DataOutputStream dataOutputStream = new DataOutputStream( connection.getOutputStream());
        dataOutputStream.writeBytes(parametrousuario);
        dataOutputStream.flush();

        InputStream inputStream = connection.getInputStream();

        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( inputStream, "UTF-8" ) );
        String linha;
        StringBuffer resposta = new StringBuffer();

        while ((linha = bufferedReader.readLine()) != null) {

            resposta.append( linha );
            resposta.append( '\r' );
        }


            bufferedReader.close();
            return resposta.toString();


    } catch (Exception erro){

        return null;

    }finally {

        if (connection !=null){

            connection.disconnect();
        }


    }


}

}

    
asked by anonymous 03.08.2017 / 22:27

2 answers

0

The method to set the send type is setRequestMethod and not getRequestMethod as used, which should be changed at the top of the connection to be as follows:

try{

    url = new URL (urlusuario);
    connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("POST"); //agora com set

Note that content-length is also not good because of a typing error:

connection.setRequestProperty( "content-lenght", ...

You should then stay:

connection.setRequestProperty( "content-length", "" + Integer.toString( parametrousuario.getBytes().length );
    
03.08.2017 / 22:58
0

You have changed the command. You are currently using getRequestMethod("POST") when you should be using setRequestMethod("POST") . Try switching get to set and see if it works.

    
03.08.2017 / 23:02