hdf hdf - 2 months ago 8
HTTP Question

Java: Passing multiple parameters to a method

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.

Answer

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:

public void callingMethod() {
    Map<String, Object> params = ImmutableMap.of(
        "param1Name", param1Value,
        "param2Name", param2Value,
    );
    makeRequest(params);
}

public void makeRequest(Map<String, Object> params) {
    HttpPost request = new HttpPost(url);
    request.addHeader("Content-Type", "application/json");
    request.setEntity(new Gson().toJson(params)));
}

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:

@Path("/v1")
public interface RestApi {
    @POST
    @Path("/objects/{objectId}/create")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    ResponseObject createObject(@PathParam("objectId") Integer objectId, RequestObject body);
}

public class RequestObject {
    public final String param1;
    public final List<Integer> param2;

    public RequestObject(String param1, List<Integer> param2) {
        this.param1 = param1;
        this.param2 = param2;
   }
}

public class ResponseObject {
    // etc
}

public static void main() {
    String url = "https://api.example.com";
    Client client = ClientBuilder.newBuilder().build().target(url);
    RestApi restApi = WebResourceFactory.newResource(RestApi.class, clientBuilder);
    ResponseObject response = restApi.createObject(12, new RequestObject("param1", ImmutableList.of(1,2,3));
}

Er, I guess the point here is that Java isn't particularly concise.