2010-02-21 14 views
52

Sono piuttosto verde con HttpClient e sto trovando la mancanza di documentazione (e/o falsamente errata) estremamente frustrante. Sto cercando di implementare il seguente post (elencato sotto) con Apache Http Client, ma non ho idea di come farlo realmente. Mi sotterrerò nella documentazione per la prossima settimana, ma forse i codificatori HttpClient più esperti potrebbero ottenere prima una risposta.Apache HttpClient che crea un modulo in più post

Messaggio:

Content-Type: multipart/form-data; boundary=---------------------------1294919323195 
Content-Length: 502 
-----------------------------1294919323195 
Content-Disposition: form-data; name="number" 

5555555555 
-----------------------------1294919323195 
Content-Disposition: form-data; name="clip" 

rickroll 
-----------------------------1294919323195 
Content-Disposition: form-data; name="upload_file"; filename="" 
Content-Type: application/octet-stream 


-----------------------------1294919323195 
Content-Disposition: form-data; name="tos" 

agree 
-----------------------------1294919323195-- 
+2

Grazie per aver chiesto il tipo di domanda direttamente correlata al debug di app Web ... L'ho trovato in Firebug e fino ad ora non sapevo come scrivere una query per emularlo! –

risposta

75

Usa MultipartEntityBuilder dal HttpMime library per eseguire la richiesta che si desidera.

Nel mio progetto lo faccio in questo modo:

HttpEntity entity = MultipartEntityBuilder 
    .create() 
    .addTextBody("number", "5555555555") 
    .addTextBody("clip", "rickroll") 
    .addBinaryBody("upload_file", new File(filePath), ContentType.create("application/octet-stream"), "filename") 
    .addTextBody("tos", "agree") 
    .build(); 

HttpPost httpPost = new HttpPost("http://some-web-site"); 
httpPost.setEntity(entity); 
HttpResponse response = httpClient.execute(httpPost); 
HttpEntity result = response.getEntity(); 

Spero che questo vi aiuterà.

(aggiornato questo post per utilizzare MultipartEntityBuilder anziché obsoleta MultipartEntity, utilizzando il codice @mtomy come esempio)

+2

MultipartEntity ora si presenta come deprecato. Sto usando Apache httpclient 4.3.3 - qualcuno sa cosa invece dovremmo usare? Trovo che le ricerche su google siano così piene di esempi MultipartEntity che non riesco a trovare nulla. – vextorspace

+11

Utilizzare MultipartEntityBuilder. Esempio breve: Entità HttpEntity = MultipartEntityBuilder.create(). AddTextBody ("field1", "value1"). AddBinaryBody ("myfile", nuovo file ("/ percorso/file1.txt"), ContentType.create (" application/octet-stream ")," file1.txt "). build(); – mtomy

13

MultipartEntity ora mostra come obsoleto. Sto usando apache httpclient 4.3.3 - qualcuno sa che cosa dovremmo usare invece ? Trovo che le ricerche su google siano così piene di esempi di MultipartEntity Non riesco a trovare nulla. - vextorspace 31 marzo '14 a 20:36

Ecco il codice di esempio in HttpClient 4.3.x

http://hc.apache.org/httpcomponents-client-4.3.x/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

import org.apache.http.entity.mime.MultipartEntityBuilder; 

HttpPost httppost = new HttpPost("http://localhost:8080" + 
     "/servlets-examples/servlet/RequestInfoExample"); 

FileBody bin = new FileBody(new File(args[0])); 
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); 

HttpEntity reqEntity = MultipartEntityBuilder.create() 
     .addPart("bin", bin) 
     .addPart("comment", comment) 
     .build(); 


httppost.setEntity(reqEntity); 

Per utilizzare la classe MultipartEntityBuilder, è necessario httpmime, che è un sottoprogetto di HttpClient

HttpClient 4.3.x:

http://hc.apache.org/httpcomponents-client-4.3.x/index.html

httpmime 4.3.x:

http://hc.apache.org/httpcomponents-client-4.3.x/httpmime/dependency-info.html

2

se la confezione uso org.apache.commons.httpclient.HttpClient, forse questo può aiutare!

HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); 
    //here should set HttpConnectionManagerParams but not important for you 
    HttpClient httpClient = new HttpClient(httpConnectionManager); 

    PostMethod postMethod = new PostMethod("http://localhost/media"); 

    FilePart filePart = new FilePart("file", new File(filepath)); 
    StringPart typePart = new StringPart("type", fileContent.getType(), "utf-8"); 
    StringPart fileNamePart = new StringPart("fileName", fileContent.getFileName(), "utf-8"); 
    StringPart timestampPart = new StringPart("timestamp", ""+fileContent.getTimestamp(),"utf-8"); 
    Part[] parts = { typePart, fileNamePart, timestampPart, filePart }; 

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, postMethod.getParams()); 
    postMethod.setRequestEntity(multipartRequestEntity); 
    httpClient.executeMethod(postMethod); 
    String responseStr = postMethod.getResponseBodyAsString(); 
+0

è per HttpClient 3.x non per 4.x. – M2E67

Problemi correlati