问题
This seems so simple, but I can't figure out why it doesn't work.
I have a Jersey service defined:
@POST
public SomeObject createSomeObject(
@QueryParam("firstParam") String firstParam,
@QueryParam("secondParam") String secondParam)
{
// Does stuff, returns the object.
}
Now, if I do a simple curl, it works fine:
curl -X POST "http://localhost:8080/path/to/service?firstParam=Bleh&secondParam=Blah
However, the following results in null for firstParam and secondParam in the Java:
$.ajax({
url: '/path/to/service',
type: 'POST',
data: {
firstParam: 'Bleh',
secondParam: 'Blah'
},
success: doStuff,
error: eek
});
This seems ridiculously straight-forward. I feel they should behave exactly the same. What am I missing? Things I've tried (but don't seem necessary):
- Adding
contentType: 'application/x-www-form-urlencoded'to theajaxcall. - Adding
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)to the Jersey service. - Wrapping the data object with
JSON.stringify(I know I need to do that whencontentType: 'json', but shouldn't have to here.
I know I can code the URL parameters myself and stuff 'em in the URL, but that seems inelegant and I shouldn't have to do that.
回答1:
If you send multiple params using POST, you've to do a application/x-www-form-urlencoded POST, that way the params are encoded in the request like:
firstParam=Bleh&secondParam=Blah
But, to consume theese params you have to annotate the function params like:
@POST
public SomeObject createSomeObject(@FormParam("firstParam") String firstParam,
@FormParam("secondParam") String secondParam) {
// Does stuff, returns the object.
}
pay attention in that the annotation is @FormParam instead of @QueryParam
Note that if you do a "normal" POST, your function can only have one param to receive de POSTed data (appart from the params assigned from query string url params)
回答2:
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded;charset=utf-8",
url: url,
data: data,
dataType: 'json',
timeout: 3000,
// jsonpCallback:"foo",
success:function(response){
console.log(response);
},
error: function(){
console.log("error!");
}
});
Above is a jquery request and just as @futuretelematics said we need contentType: "application/x-www-form-urlencoded;charset=utf-8". And then add @Consumes( {MediaType.APPLICATION_FORM_URLENCODED}) in the Jersey service.
@POST
@Produces({ MediaType.APPLICATION_JSON})
@Consumes( {MediaType.APPLICATION_FORM_URLENCODED})
public String execute(@FormParam("stoYardName") String data,
@FormParam("domTree") String domTree
) {
.........
};
来源:https://stackoverflow.com/questions/16704042/jquery-not-posting-url-arguments-to-jersey-service