2016-10-04 65 views
0

将多个参数传递给方法然后将这些参数放入有效载荷中的正确方法是什么?Java:将多个参数传递给方法

的方法应该发送一个HTTP请求瓦特/有效载荷到服务器(和接收来自它的响应),这工作得很好:

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())); 

    ... 

但是,我认为,应该有另一种更高效(和审美)的方式来执行此操作。

+0

你认为它存在更高效/美观吗? – Spotted

回答

1

这真的取决于你需要你的方法是多么可重用。如果您只想发送带有4个参数集的请求,那可能要尽可能简洁。如果你想发送任意的JSON数据,你可能想要在方法外部构造JSONObject,并将其作为单个参数传递。

如果您正在寻找小的语法胜利,您可能需要查看google GuavaGson库。他们会让你稍微凝结这:

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))); 
} 

或者,如果你有一个整体REST API进行交互,你可以使用库像泽西它作为一个Java类建模,然后创建一个代理以隐藏你正在发出HTTP请求的事实:

@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)); 
} 

呃,我猜这里的重点是Java不是特别简洁。

0

你可以做

public static JSONObject myMethod(String ... params) { 
    //access each one like so: 
    //params[0] 
    //params[1] 
} 
//... 
myMethod("here", "are", "multiple", "parameters"); 

然而,这限制了参数全部是字符串,你可以在一个JSONObject发送为开始,然后跳过方法中的序列化的参数。