2012-05-15 24 views
9

Ho bisogno di un semplice esempio di codice per l'invio della richiesta di post http con parametri di post che ottengo dagli input del modulo. Ho trovato Apache HTTPClient, ha un'API molto ampia e molti esempi sofisticati, ma non sono riuscito a trovare un semplice esempio di invio della richiesta di post http con parametri di input e risposta al testo.Come inviare una semplice richiesta di post http con parametri di post in java

Aggiornamento: Sono interessato ad Apache HTTPClient v.4.x, poiché 3.x è deprecato.

+0

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

risposta

3

HTTP POST esempio di richiesta usando 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

ho tirato questo codice da un progetto android da Andrew Gertig che ho usato nella mia applicazione. Ti permette di fare un HTTPost. Se avessi tempo, creerei un esempio POJO, ma si spera che si possa sezionare il codice e trovare quello che ti serve.

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

Ecco il codice di esempio per Http POST, utilizzando 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

Grazie, Sumit. Ho bisogno di questo esempio, ma il tuo esempio utilizza Apache HttpClient v. 3.x, che è deprecato (anche se non sono riuscito a trovare i jar della versione 3.x nella loro pagina di download). Ora suggeriscono HttpClient v.4.1, che ha API diverse, ma non trovo come inserire i parametri del post con questa API. – Arshak

+3

Ho trovato i vasi per httpClient v.3 e funziona per me, ma in ogni caso mi chiedo perché è così complicato inviare una semplice richiesta di posta con v. 4.1 e in Java in generale. – Arshak

+0

hi puoi aggiungere un parametro aggiuntivo che accetta un oggetto file? Grazie – Secondo