java - 带有 @FormParam 的 PUT 方法

标签 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"}

谢谢

最佳答案

表单参数数据仅在您提交...表单数据时才会出现。将资源的 @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;
}

然后在您的客户端设置:

  • 内容类型:多部分/表单数据
  • 添加登录名密码的表单变量

顺便说一句,假设这不是为了学习,您将需要使用 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);
}

关于java - 带有 @FormParam 的 PUT 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545351/

相关文章:

javascript - 如何编写此正则表达式以获取多行数据并转换为 JSON 数组

javascript - 如何将 PHP JSON 转换为 JS 数组

rest - 重用模型类进行 API 测试有什么缺点?

c++ - 在 Casablanca 中设置基本 HTTP 身份验证

java - Android java通过特殊字符分割字符串失败

java - synchronized vs ReentrantLock 无竞争锁

java - 在新的执行线程中使用 catch throwable 或 catch Exception

java - 如何从命令提示符编译实现包的java程序

php - JSONPath 查询获取节点名称?

http - 使用 NodeJS,解析不一定结束的文件上传的最佳方法是什么?