What is the proper way to pass multiple parameters to a method and then put those parameters into a payload?
The method should send an HTTP request w/ payload to a server (and receive a response from it) and this works just fine:
public static JSONObject myMethod(String parameterOne, JSONArray parameterTwo, String parameterThree, long parameterFour) {
...
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "application/json");
JSONObject payload = new JSONObject();
payload.put("parameterOne", parameterOne);
payload.put("parameterTwo", parameterTwo);
payload.put("parameterThree", parameterThree);
payload.put("parameterFour", parameterFour);
request.setEntity(new StringEntity(payload.toString()));
...
However, I believe that there should be another, more efficient (and aesthetic) way to perform this.
You could do
However this restricts the parameters to all be strings, you could send in a JSONObject as a parameter to begin with and skip the serialization within the method.
It really depends on how re-usable you need your method to be. If you only ever want to send requests with that set of 4 parameters, that's probably about as concise as you can get. If you're looking to send arbitrary JSON data, you'd probably want to construct the JSONObject outside the method, and pass it in as a single argument.
If you're looking for small, syntactic wins, you might want to check out the google Guava and Gson libraries. They'd let you slightly condense this to:
Alternatively, if you're interacting with a whole REST API, you could use a library like Jersey to model it as a Java class, and then create a proxy to hide the fact that you're making an HTTP request at all:
Er, I guess the point here is that Java isn't particularly concise.