2012-05-15 15 views
9

Necesito un ejemplo de código simple para enviar una solicitud http post con los parámetros de publicación que obtengo de las entradas de formulario. Encontré Apache HTTPClient, tiene API muy accesible y muchos ejemplos sofisticados, pero no pude encontrar un ejemplo simple de envío de solicitudes HTTP con parámetros de entrada y obtención de respuesta de texto.Cómo enviar una solicitud http post sencilla con parámetros de publicación en java

Actualización: Estoy interesado en Apache HTTPClient v.4.x, ya que 3.x está en desuso.

+0

http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet- Tutorial-Primer-Servlets.html –

Respuesta

3

HTTP POST ejemplo solicitud utilizando Apache HttpClient v.4.x

HttpClient httpClient = HttpClients.createDefault(); 
HttpPost httpPost = new HttpPost(url); 
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN); 
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN); 
HttpEntity multipart = builder.build(); 
httpPost.setEntity(multipart); 
HttpResponse response = httpClient.execute(httpMethod); 
3

Saqué el código de un proyecto Android por Andrew Gertig que he utilizado en mi solicitud. Le permite hacer un HTTPost. Si tuviera tiempo, crearía un ejemplo POJO, pero con suerte, puedes diseccionar el código y encontrar lo que necesitas.

Arshak

https://github.com/AndrewGertig/RubyDroid/blob/master/src/com/gertig/rubydroid/AddEventView.java

private void postEvents() 
{ 
    DefaultHttpClient client = new DefaultHttpClient(); 

    /** FOR LOCAL DEV HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */ 
    HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents"); 
    JSONObject holder = new JSONObject(); 
    JSONObject eventObj = new JSONObject(); 

    Double budgetVal = 99.9; 
    budgetVal = Double.parseDouble(eventBudgetView.getText().toString()); 

    try { 
     eventObj.put("budget", budgetVal); 
     eventObj.put("name", eventNameView.getText().toString()); 

     holder.put("myevent", eventObj); 

     Log.e("Event JSON", "Event JSON = "+ holder.toString()); 

     StringEntity se = new StringEntity(holder.toString()); 
     post.setEntity(se); 
     post.setHeader("Content-Type","application/json"); 


    } catch (UnsupportedEncodingException e) { 
     Log.e("Error",""+e); 
     e.printStackTrace(); 
    } catch (JSONException js) { 
     js.printStackTrace(); 
    } 

    HttpResponse response = null; 

    try { 
     response = client.execute(post); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
     Log.e("ClientProtocol",""+e); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     Log.e("IO",""+e); 
    } 

    HttpEntity entity = response.getEntity(); 

    if (entity != null) { 
     try { 
      entity.consumeContent(); 
     } catch (IOException e) { 
      Log.e("IO E",""+e); 
      e.printStackTrace(); 
     } 
    } 

    Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show(); 

} 
15

Aquí es el código de muestra para Http POST, utilizando Apache HTTPClient API.

import java.io.InputStream; 
import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.methods.PostMethod; 


public class PostExample { 
    public static void main(String[] args){ 
     String url = "http://www.google.com"; 
     InputStream in = null; 

     try { 
      HttpClient client = new HttpClient(); 
      PostMethod method = new PostMethod(url); 

      //Add any parameter if u want to send it with Post req. 
      method.addParameter("p", "apple"); 

      int statusCode = client.executeMethod(method); 

      if (statusCode != -1) { 
       in = method.getResponseBodyAsStream(); 
      } 

      System.out.println(in); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 
} 
+0

Gracias, Sumit. Necesito tal ejemplo, pero su ejemplo está usando Apache HttpClient v. 3.x, que está en desuso (incluso yo no pude encontrar los archivos de versión 3.x en su página de descarga). Ahora sugieren HttpClient v.4.1, que tiene API diferente, pero no encuentro cómo poner parámetros de publicación con esta API. – Arshak

+3

Encontré los frascos para httpClient v.3 y me funciona, pero de todos modos me pregunto por qué es tan complicado enviar una simple solicitud posterior con la v. 4.1 y en general con Java. – Arshak

+0

hola puede agregar un parámetro adicional que acepte un objeto de archivo? Gracias – Secondo

Cuestiones relacionadas