简体   繁体   中英

HttpPost parameters BasicNameValuePair in Java

I have to pass a parameters list to an Http POST call.

The actual JSON expected from the server is:

{
 "par1": "val1",
 "par1": "val1",
 "par3": ["val1", "val2", "val3"]
}

Here's the Java stub:

List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("par1", "val1"));
parameters.add(new BasicNameValuePair("par2", "val2"));
parameters.add(new BasicNameValuePair("par3", "["val1", "val2", "val3"]"));

this is how I pass parameters to HttpPost object:

httpPost.setEntity(new UrlEncodedFormEntity(parameters));

The endpoint expects an array as the 4° line says and I have no idea on how to pass it as array.

Tried searching on Stackoverflow and found the following solutions:

//inside for loop
parameters.add(new BasicNameValuePair(String.format("par[%d]", incremental), "value"+incremental));

or

//inside for loop
parameters.add(new BasicNameValuePair("par[]", "value"+incremental));

or

String values = "" +
            "[" +
                "\"val1\"," +
                "\"val2\"," +
                "\"val3\""
            "]";


parameters.add(new BasicNameValuePair("par3", values ));

Actually, I cannot debug the server side so I can't say if they're correct or not. Since now none of them had worked.

How can I make it on java?

The actual JSON from server is

"par1": "val1",

"par1": "val1",

"par3": ["val1","val2","val3"]

I think the problem is That you are getting

"par1": "val1"

Twice from the server side. Change the second to

par2 : 'val2'

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