我有一个POST方法(需要一些JSON数据)。我还想访问路径参数“ id”进行处理。但是,当我使用“ @PathParam”时,我得到了传递给请求的JSON正文。下面是我的代码:
@Path("/products")
public class PurchaseService {
@POST
@Consumes("application/json")
@Path("{id}/purchase")
@Produces(MediaType.APPLICATION_JSON)
public String doPurchaseForUser(@PathParam("id") String id) {
String result = null;
System.out.println("Product : " + id);
return id;
}
}
如果我以-{“ user_id”:123}的形式传递POST正文,则上面代码中的id变量将保存此值,而不是URI中的id值。我在做什么错了?
答案 0 :(得分:0)
用#include <iostream>
#include <vector>
using namespace std;
int main() {
int candidates = 0; // Number of candidates
int voters = 0; // Number of voters
cout<<"Enter the number of candidates and voters\n";
cin >> candidates >> voters;
vector<int> result(candidates, 0); // Vector to hold the results
// Do voting; you can count the votes immediately,
// so no need of a vector to hold the votes.
int vote = 0;
for( int i = 0; i < voters; ++i )
{
cout<<"Enter vote by voter "<<i+1<<':';
while( (vote <= 0) || (vote > candidates) )
cin >> vote; // if the entered votes are invalid, user enters the number again
++result[vote-1]; // credit candidate for whom the vote was cast
vote = 0; // reset vote
};
// Find the winner; there are standard C++ functions for this,
// but we will do it by hand for now.
int winner = 0;
cout<<"\nResults: \n";
for( int j = 0; j < candidates; ++j )
{
if(result[winner] < result[j])
winner = j; // If someone has more votes, he is the winner
cout<<"Candidate "<<(j+1)<<": "<<result[j]<<'\n';
}
cout<<"The winner is: "<<winner+1<<"\n";
return 0;
}
注释方法时,意味着您正在告诉Web服务:此方法正在等待json格式的对象作为参数。这就是为什么您的String id使用json内容的原因。
@Consumes ("application/json")
公共类PurchaseService {
@Path("/products")
}
您的通话网址如下所示
@POST
@Consumes("application/json")
@Path("/purchase")
@Produces(MediaType.APPLICATION_JSON)
public String doPurchaseForUser(@QueryParam("id") String id,JsonObject jsonContent) {
String result = null;
System.out.println("Product : " + id);
return id;
}
答案 1 :(得分:0)
您输入了错误的@PathParam
。它应该是javax.ws.rs.PathParam
。您可能正在导入websocket一个(当您具有javaee-api依赖项时,这是一个常见错误)。