【问题标题】:PathParam value null in Jersey web serviceJersey Web 服务中的 PathParam 值为 null
【发布时间】:2013-02-28 10:14:53
【问题描述】:

我是网络服务的新手,我是编写代码以在 Android 中调用 Jersey 网络服务的新手。但是我得到 null 作为 PathParam 的参数值。 请帮助我了解我的代码有什么问题。

以下是 Android 中 Web 服务调用的代码:

HttpClient httpClient = new DefaultHttpClient();  
HttpPost httpPost = new HttpPost(url);  

httpPost.setHeader("content-type", "application/json");  
JSONObject data = new JSONObject();  

try {  
   data.put("email_id", strEmailId);  
   data.put("password", strPassword);  
   Log.d("1", data.toString());  
   HttpEntity entity;  
   StringEntity s = new StringEntity(data.toString());  
   entity = s;  
   httpPost.setEntity(entity);  
   HttpResponse response = httpClient.execute(httpPost);  
}

这是网络服务代码

@POST  
@Consumes(MediaType.APPLICATION_JSON)  
@Produces(MediaType.APPLICATION_JSON)  
@Path("/dbconnect")  
public String connectToDbTest(@PathParam("email_id") String email_id,@PathParam("password") String password) {  
   System.out.println(email_id+" "+password);  
}  

【问题讨论】:

    标签: java android web-services jersey jax-rs


    【解决方案1】:

    我不确定使用 字符串实体 类,但在服务器代码上,如果您使用 Path 参数,则应在使用前在模板中声明参数。例如

        @Path("/dbconnect/{email_id}/{password}")
    

    服务器收到的网址应该是

        protocol://server/context/dbconnect/email@id.com/password
    

    虽然通过 url 传递密码是一个非常糟糕的主意,但在功能上,它会起作用。

    【讨论】:

    • 但是我没有在 url 的路径中传递值,而是在请求正文中传递值。所以我不能让它像@Path("/dbconnect/{email_id}/{password}")
    • mitratul 回答它是正确的。要接收正文并保留您的实际路径,请更改方法的签名以接收 JSON 内容:public String connectToDbTest(String content) { ... }(删除 @PathParam,因为它们使用错误)。您可以从内容字符串中手动提取变量或使用 JAXB 等框架自动将 JSON 字符串转换为模型对象。
    猜你喜欢
    • 1970-01-01
    • 2014-09-13
    • 2017-05-24
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多