删除“/”当可选参数为null时从api调用 [英] Remove "/" from api call when optional parameter is null
问题描述
我们正在使用 RESTful Web Services(Jersey)进行Java上的API调用。虽然API需要可选参数,但我们这样做:
We are using RESTful Web Services (Jersey) for API calls on java. While API needs optional parameter, we are doing as:
api-interface/user/userid/9000/companyid/90909/{optionalparameter*}
当没有可选参数时我们必须调用此api:
and we have to call this api when there is no optional parameter as:
api-interface/user/userid/9000/companyid/90909/
需要的是:
案例:1如果存在可选参数
api-interface/user/userid/9000/companyid/90909/name/john/address/MA/age/34
案例:2如果可选参数不存在。
api-interface/user/userid/9000/companyid/90909
我目前的实施是:
@GET
@Path("user/companyid/{companyid}/userid/{userid}/{optionalparameter:.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserList(@PathParam("companyid") String companyId, @PathParam("userid") String userId,
@PathParam("optionalparameter") String syncDate) throws BadRequestException, InternalServerException {
//parsing the param.
}
在上面的代码中,我需要添加尾随/但是如果有人不想传递那些参数,我正在寻找删除这个尾随/的方法。
我跟着这个链接但它没有奏效而上述参数的长度大于1.
I followed this link but it didn't worked while the preceding parameter's length is more then 1.
请建议我最好的方式。
推荐答案
查看您的参考资料,您试过这个:
@Path("userid/{userid}/companyid/{companyid}{optparam:(/[^/]+?)*}")
public Response getLocation(
@PathParam("userid") int userid,
@PathParam("companyid") int companyid,
@PathParam("optparam") String optparam) {
String[] params = parseParams(optparam);
...
}
private String[] parseParams(String params) {
if (params.startsWith("/")) {
params = path.substring(1);
}
return params.split("/");
}
这应该有效,在一个数组中提供所有参数。
That should work, giving you all the parameters in a single array.
编辑:我更新了搜索字符串并在本地安装时验证了它。
EDIT: I have updated the search string and verified it on a local install.
这篇关于删除“/”当可选参数为null时从api调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!