antivirus
Óptima protección antivirus: Soluciones de seguridad en Internet de G Data para PC.

jueves, 19 de febrero de 2015

Hacer una petición HTTP por el método POST con java

Podemos hacer una petición HTTP por el método POST con la aplicación cURL con la siguiente orden de terminal

    curl -d "param=valor&otro=27"  http://servidor.com/script.php

Y esa misma petición, en código java, se puede hacer con:

        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httppost = new HttpPost("http://servidor.com/script.php");
           
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("param", "valor" ));
            nameValuePairs.add(new BasicNameValuePair("otro", "27" ));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> resHandle = new BasicResponseHandler();
            response = httpclient.execute(httppost,resHandle);

        } catch (ClientProtocolException e) {
            // algo falla
        } catch (IOException e) {
            // algo falla
        }