2015-03-19 8 views
5

यह मेरी पहली बार मल्टीपार्ट अनुरोध भेज रहा है और यहां खोदने के बाद, मुझे और भी भ्रमित हो गया है, इसलिए "सही" तरीके से संबंधित कोई भी सहायता बहुत सराहना की जाएगी।जावा में HttpURLConnection का उपयोग कर मल्टीपार्ट POST अनुरोध कैसे भेजें?

मेरे पास एक फ़ंक्शन है, जो प्राप्त करना चाहिए: फ़ाइल पथ और JSON का एक स्ट्रिंग प्रतिनिधित्व और मल्टीपार्ट का उपयोग कर सर्वर को POST अनुरोध भेजें।

मैं boundary और "multipart/form-data" सामग्री प्रकार का उपयोग करने के लिए जब यकीन नहीं है, और addPart और addTextBody, और जब (या क्यों) के बीच अंतर यह हमेशा Content-Disposition: form-data; name=\

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.. 

लिखा है अब मैं नहीं कर रहा हूँ यकीन है कि आगे कैसे बढ़ना है, फ़ाइल और json स्ट्रिंग लिखने के लिए और कैसे मैं इस कोड को देखा:

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

लेकिन मैं समझता हूँ कि यह कैसे मेरी 0 से जुड़ा है नहीं कर पा रहे।

क्या आप कृपया मदद कर सकते हैं?

+0

exacly मेरी समस्या है कि। मुझे MultipartEntityBuilder और HttpURLConnection का उपयोग करने के बारे में अधिक जानकारी नहीं मिल रही है। –

उत्तर

1

नमूना HTML प्रपत्र: बहुखण्डीय प्रपत्र प्रविष्ट करने के लिए

<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> 

जावा कोड:

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 
संबंधित मुद्दे