lunes, 11 de abril de 2011

HTTP response code: 411 (solución para este error)

Error 411 en respuesta a un POST por HTTP

Estuve 2 horas tratando de averiguar porqué se generaba el error 411 al enviar datos mediante POST a un pequeño script de pruebas en PHP.

El error 411 indica que hay un error en el tamaño indicado en el encabezado del POST, este tamaño hace referencia al numero de bytes de los datos a enviar en el POST hacia el servidor, este número de bytes se envía mediante el encabezado: "Content-Length".

Todo estaba bien puesto, sin embargo el error prevalecía. Revisé todo, y el error persistió, hasta que di con la falla:
el método OutputStream .flush() causa el error 411 por agregar alguna discordancia con el parámetro de encabezado 'Content-Length'

Cómo resolverlo y enviar un POST desde un Midlet:

public static String post(String url,String datos) 
  throws IOException
    {
        HttpConnection c = null;
        InputStream is = null;
        OutputStream os = null;
        int rc;
        String respuesta="";

        try {
            c =(HttpConnection)Connector.open(
                url,Connector.READ_WRITE);
            byte[] request_body = datos.getBytes();
            c.setRequestMethod(HttpConnection.POST);
            c.setRequestProperty("User-Agent","Mozilla/4.0");
            c.setRequestProperty("Content-Type"
                ,"application/x-www-form-urlencoded");
            c.setRequestProperty("Content-Length"
              ,Integer.toString(request_body.length));
            
            os = c.openOutputStream();
            os.write(request_body);
            // esta linea causa el error 411
            // os.flush();  <-- quitar esto

            rc = c.getResponseCode();
            if (rc != HttpConnection.HTTP_OK) {
                throw new IOException(
                 "HTTP response code: " + rc);
            }

            is = c.openInputStream();
            int len = (int)c.getLength();
            if (len > 0) {
                 int actual = 0;
                 int bytesread = 0 ;
                 byte[] data = new byte[len];
                 while ((bytesread != len) && (actual != -1)) {
                    actual = is.read(data, bytesread, len - bytesread);
                    bytesread += actual;
                     respuesta += new String(data);
                 }
            } else {
                int ch;
                while ((ch = is.read()) != -1) {
                    //procesar((byte)ch);
                }
            }
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Not an HTTP URL");
        } finally {
            if (is != null)
                is.close();
            if (os != null)
                os.close();
            if (c != null)
                c.close();
        }
        return respuesta.trim();
    }





No hay comentarios:

Publicar un comentario