如何将请求中的JSON数据发送到RESTWeb服务

如何将请求中的JSON数据发送到RESTWeb服务,json,rest,Json,Rest,我创建了一个rest Web服务,在一个方法中包含以下代码: @POST @Path("/validUser") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JSONObject validUserLogin(@QueryParam(value="userDetails") String userDetails){ JSONObject json = null;

我创建了一个rest Web服务,在一个方法中包含以下代码:

@POST
@Path("/validUser")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject validUserLogin(@QueryParam(value="userDetails") String userDetails){
    JSONObject json = null;
    try{
        System.out.println("Service running from validUserLogin :"+userDetails);
        json = new JSONObject(userDetails);
        System.err.println("UserName : "+json.getString("userName")+" password : "+json.getString("password"));
        json.put("httpStatus","OK");
        return json;            
    }
    catch(JSONException jsonException) {
       return json;
    }
}
我在客户端代码中使用Apache API。下面的客户端代码通过将一些用户相关数据发布到此服务来调用此服务:

public static String getUserAvailability(String userName){
    JSONObject json=new JSONObject();

    try{
        HttpContext  context = new BasicHttpContext();
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        URI uri=new URIBuilder(BASE_URI+PATH_VALID_USER).build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json");
        json.put("userName", userName);
        StringEntity stringEntity = new StringEntity(json.toString());
        request.setEntity(stringEntity);
        HttpResponse response = client.execute(request,context);
        System.err.println("content type : \n"+EntityUtils.toString(response.getEntity()));
    }catch(Exception exception){
        System.err.println("Client Exception: \n"+exception.getStackTrace());
    }
    return "OK";
}
问题是,我可以调用该服务,但我在请求到服务中传递的参数结果为null


我是否在请求中以错误的方式发布数据。我还想在响应中返回一些JSON数据,但我无法获取这些数据。

在Zack的帮助下,我了解了一些如何解决问题的方法, 我使用了jackson core jar并更改了服务代码,如下所示

@POST
@Path("/validUser")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject validUserLogin(String userDetails){
  ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readValue(userDetails, JsonNode.class);

        System.out.println("Service running from validUserLogin :"+userDetails);

        System.out.println(node.get("userName").getTextValue());
        //node.("httpStatus","OK");
        return Response.ok(true).build();       

}

所以您可以看到RESTWeb服务接收到请求,但是userDetails字符串在那里是空的?您确定请求发送到服务吗?是的,我在控制台中打印字符串作为。“从validUserLogin运行的服务:null”在客户端代码中,您将“用户名”与
json.put(“用户名”)
放在一起,您的意思是将
json.put(“userDetails”)
放在一起,以便它与REST服务中的参数名匹配吗?在这种情况下这有关系吗?是的,我也试过了,但是同样的错误,我想我无法正确地发布数据。有没有一种方法可以只发送字符串,而不是作为JSON对象,而是作为字符串?这个答案中有一条注释,您可以看到它说“只传递值(即不作为JSON对象),它应该可以工作,根据”我改变了返回响应的方式:return response.ok(true.entity(“ok”).build();它开始工作了。