简体   繁体   中英

How to use http POST data section - Java

I have many working https POST connections within my application, all sending simple name/value pairs in the form section.

I have been testing new communications using https://httpbin.org/post which bounces back my request so I can see how it looks.

A returned request looks like:

{  
    "args": {},   
    "data": "",   
    "files": {},   
    "form": {    
        "data": "Test file #1\nThis file is for testing the file uploading",     
        "name": "testFile1.txt"  
        ...
    },   
    "headers": {    
        "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",     
        "Content-Length": "193",     
        "Content-Type": "application/x-www-form-urlencoded",     
        "Host": "httpbin.org",     
        "User-Agent": "Java/1.8.0_45"  
    },   
    "json": null,   
    ...  
    "url": "https://httpbin.org/post"
}

I can put data into the "form" section (as above) using httpsConn.getOutputStream().write(data) , where httpsConn is my HttpsURLConnection & data is my byte[] of name/value pairs.

AND I can put data into the "files" section using (among other bits, I think these are the important pieces of code)

request.writeBytes("Content-Disposition: form-data; name=\\"data\\"; filename=\\"testFile1.txt\\"\\r\\n");
int data; while ((data = fileInputStream.read()) != -1) { request.write(data); }

where request is my DataOutputStream

The above options work to send a file in the "form" or "files" sections, however I don't really understand how it's defining in which section the information should be sent.

How would I go about adding information to the "data" or "args" sections?

In the simple scenario where you just want data to be sent as key value pairs, use form data.. It is simple to implement and easy to work with..

However in the case when you want to send complex data like a CSV file or any such huge data, send them as files with proper content disposition as multi part data or a relevant one.

Args is usually used in the case of get request where the back end needs to send back some data based on user input.. We typically don't use args for posting data to backend as it is semantically not right..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM