2015-03-19 28 views
5

İlk defa çok parçalı talepler gönderiyorum ve burada kazmaya başladım, daha da kafam karıştı, bu yüzden "doğru" yol ile ilgili herhangi bir yardım çok takdir görecek.Java'da HttpURLConnection kullanarak çoktan POST isteği nasıl gönderilir?

Aşağıdakileri yapmam gereken bir işlev var: JSON'un dosya yolu ve Dize sunumu ve POST isteğini sunucuya çok yollu kullanarak gönderme.

ben her zaman ben değilim Şimdi

public String foo(String filePath, String jsonRep, Proxy proxy) 
{ 
    File f = new File(filePath); 
    HttpURLConnection connection; 
    connection = (HttpURLConnection) url.openConnection(proxy); 
    connection.setRequestProperty("Content-Type", "multipart/form-data"); // How should I generate boundary? Should it be added here? 

    if (myMethod == "POST") 
    { 
     connection.getOutputStream().write(? Both the json string and the file bytes??); 
     } 


.... checking there is no error code etc.. 

return ReadResponse(connection) // read input stream.. 

Content-Disposition: form-data; name=\ yazılır boundary ve "multipart/form-data" içerik türünü ne zaman kullanılacağını emin değilim ve addPart ve addTextBody ve ne zaman (ya da neden) arasındaki fark devam etmek, ne kadar emin dosya ve json dize yazmak için ve nasıl bu kodu gördük:

MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
builder.addPart("upfile", fileBody); 
builder.addPart("text1", stringBody1); 
builder.addPart("text2", stringBody2); 

Ama benim 0 bağlanır anlamak gibi olamaz.

Lütfen yardım edebilir misiniz?

+0

exacly benim sorundur. MultipartEntityBuilder ve HttpURLConnection kullanımı hakkında fazla bilgi bulamıyorum. –

cevap

1

örnek HTML formu: Çok parçalı formu submiting için

<form method="post" action="http://127.0.0.1/app" enctype="multipart/form-data"> 
<input type="text" name="foo" value="bar"><br> 
<input type="file" name="bin"><br> 
<input type="submit" value="test"> 
</form> 

Java kodu:

MultipartEntityBuilder mb = MultipartEntityBuilder.create();//org.apache.http.entity.mime 
    mb.addTextBody("foo", "bar"); 
    mb.addBinaryBody("bin", new File("testFilePath")); 
    org.apache.http.HttpEntity e = mb.build(); 

    URLConnection conn = new URL("http://127.0.0.1:8080/app").openConnection(); 
    conn.setDoOutput(true); 
    conn.addRequestProperty(e.getContentType().getName(), e.getContentType().getValue());//header "Content-Type"... 
    conn.addRequestProperty("Content-Length", String.valueOf(e.getContentLength())); 
    OutputStream fout = conn.getOutputStream(); 
    e.writeTo(fout);//write multi part data... 
    fout.close(); 
    conn.getInputStream().close();//output of remote url 
İlgili konular