使用@FormParam的PUT方法

时间:2013-03-21 10:48:17

标签: java json rest put form-parameter

如果我有类似的话:

@PUT
@Path("/login")
@Produces({"application/json", "text/plain"})
@Consumes("application/json")
public String login(@FormParam("login") String login, @FormParam("password") String password) throws Exception
{
    String response = null;
    response = new UserManager().login(login, password);
    return response;
}

如何输入两个参数来测试我的REST服务(在“内容”字段中)? 不是这样的:

{"login":"xxxxx","password":"xxxxx"}

由于

1 个答案:

答案 0 :(得分:1)

表单参数数据仅在您提交...表单数据时才会出现。将资源的@Consumes类型更改为multipart/form-data

@PUT
@Path("/login")
@Produces({ "application/json", "text/plain" })
@Consumes("multipart/form-data")
public String login(@FormParam("login") String login,
        @FormParam("password") String password) {
    String response = null;
    response = new UserManager().login(login, password);
    return response;
}

然后在您的客户端,设置:

  • 内容类型:multipart / form-data
  • loginpassword
  • 添加表单变量

在旁注中,假设这不是用于学习,您将需要使用SSL保护您的登录端点,并在通过网络发送密码之前对其进行哈希处理。


修改

根据您的评论,我提供了一个使用所需表单数据发送客户端请求的示例:

try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost(BASE_URI + "/services/users/login");

    // Setup form data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("login", "blive1"));
    nameValuePairs.add(new BasicNameValuePair("password",
            "d30a62033c24df68bb091a958a68a169"));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute request
    HttpResponse response = httpclient.execute(post);

    // Check response status and read data
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String data = EntityUtils.toString(response.getEntity());
    }
} catch (Exception e) {
    System.out.println(e);
}