2016-10-04 24 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發送爲開始,然後跳過方法中的序列化的參數。