【发布时间】:2019-06-05 03:08:30
【问题描述】:
我使用 Laravel 5 开发了一个 API RESTful 服务(后端),并使用 POSTMAN 对其进行了测试。有几个资源可以通过 GET 和 POST 请求获取信息,它们与 POSTMAN 一起工作得很好。我开始使用带有 Jersey 的 Java 客户端测试 API。 GET 方法适用于这样的代码,响应是一个 json,我用 Jackson 解析它。
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(ClientUrl);
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
Response mResponse = invocationBuilder.get();
我要测试的下一个方法是登录,使用 POST 方法。 使用 POSTMAN,我在标题中使用键“Content-Type”+ 值“application/x-www-form-urlencoded”,并在正文中发送带有此信息的 Json
{"email":"xxxxxx@gmail.com", "password":"xxxxxxxxxx"}
要在 Jersey 中使用 POST 方法,我使用下一个代码
Client client = ClientBuilder.newClient();
Form mForm = new Form();
mForm.param("email", email);
mForm.param("password", password);
WebTarget target = client.target(Utils.URL_LOGIN);
//As stated in the documentation, the APPLICATION_FORM_URLENCODED =
//"application/x-www-form-urlencoded"
Builder request = target.request(MediaType.APPLICATION_FORM_URLENCODED);
//I print the request to verify the request
print(request.toString());
Response response = request.post(Entity.form(mForm));
//I print the response to verify the response received and also the code
print("Response: " + response.toString());
print("Code: " + response.getStatus());
String result = response.readEntity(String.class);
response.close();
print(result);
当我打印 request.toString() 时,我得到了这个
org.glassfish.jersey.client.JerseyInvocation$Builder@65e579dc
当打印响应时
Response: InboundJaxrsResponse{context=ClientResponse{method=POST, uri=http://www.dance-world.com/api/login, status=200, reason=OK}}
收到的状态是 200,但是当我打印 response.readEntity 时,我得到了我在后端使用的响应,用于那些服务器没有收到请求信息的情况。
{"code":400,"status":"error","message":"No data attached to the request"}
当我使用 POSTMAN 并且结果为 200 时,我成功接收到 Token 作为字符串。
我不知道我的错误是什么,因为我正在关注文档中的代码以及 RESTful Java with JAX-RS 2.0 一书
【问题讨论】:
-
'我在标题中使用键“Content-Type”+值“application/x-www-form-urlencoded”,在正文中我发送一个 Json' .为什么?此内容类型不适合 JSON。
-
卢茨霍恩,感谢您的评论。
标签: java json post request jersey