Error creating PHP connection

Asked

Viewed 37 times

0

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

I’m new in the field, could 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();
        }


    }


}

}

2 answers

0


The method to define the sending type is setRequestMethod and not getRequestMethod how it was used, which should be changed right at the top of the connection to stay as follows:

try{

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

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

Attention that the content-length also not well due to a write error:

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

Should then stay:

connection.setRequestProperty( "content-length", "" + Integer.toString( parametrousuario.getBytes().length );
  • Thank you very much Isac. gave it right.

0

You changed the command. At the moment you are using getRequestMethod("POST") when you should be using the setRequestMethod("POST"). Try to change the get for set and see if it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.