java

2012-05-15 9 views
9

içinde post parametresi ile basit http post isteği nasıl gönderilir? Forma girişlerinden aldığım post parametrelerle http post isteği gönderme basit bir kod örneğine ihtiyacım var. Apache HTTPClient'i buldum, çok çeşitli API'ye ve çok sayıda karmaşık örneğe sahibim, ancak giriş parametreleriyle http gönderisi isteği göndermek ve metin yanıtı almak için basit bir örnek bulamadım.java

Güncelleme: Apache HTTPClient v.4.x ile ilgileniyorum, 3.x kullanımdan kaldırılmıştır.

+0

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

cevap

3

HTTP POST talebi, örneğin 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

benim uygulamada kullanmış Andrew Gertig tarafından bir Android projesinden bu kodu çekti. Bir HTTPost yapmanıza izin verir. Zamanım olsaydı, POJO örneği oluşturabilirdim, ama umarım, kodu inceleyebilir ve neye ihtiyacın olduğunu bulabilirsin.

Arşak

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

İşte Apache HTTPClient API kullanarak Http POST için örnek kod. Apache HttpClient kullanılarak

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

Teşekkür ederim, Sumit. Bu tür bir örneğe ihtiyacım var, ancak örnekte kullanımdan kaldırılmış olan Apache HttpClient v. 3.x kullanıyor (hatta indirme sayfasında 3.x sürüm küplerini bulamadım). Şimdi farklı API'ye sahip HttpClient v.4.1'i önerirler, ancak bu API ile post parametrelerini nasıl yazacağımı bulamıyorum. – Arshak

+3

httpClient v.3 için kavanozlar buldum ve bu benim için çalışıyor, ama neyse neden 4.1 ve genel olarak java ile basit posta isteği göndermek için bu kadar karmaşık olduğunu merak ediyorum. – Arshak

+0

Merhaba, bir dosya nesnesini kabul eden ek parametre ekleyebilir misiniz? Teşekkürler – Secondo