我正在尝试使用 Jersey 2.13 作为服务器,Vaadin 7.3.3 作为“客户端”来创建一个小型 REST 服务,但我的想法是请求可以来自任何地方(不仅仅是 Vaadin,这就是我不这样做的原因' 在请求时使用一个 bean)。假设用户已经注册,请求只是检查他是否存在,并返回 token 。我有一个 POST URL,https://localhost:8443/logins
,接收
{
"login-request":
{
"username":<insert username>,
"password":<insert password>
}
}
并返回:
{
"login-token":
{
"token":<insert token>
}
}
我的客户请求代码是:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://127.0.0.1:8443/").path(appName + "/logins");
//build JSON Object
HashMap<String, String> userMap = new HashMap<>();
userMap.put("username", user.getUsername());
userMap.put("password", user.getPassword());
//JSON logins request!
JSONObject jsonLoginRequest = new JSONObject();
try {
jsonLoginRequest.put("login-request", userMap);
} catch (JSONException e) {
e.printStackTrace();
}
return target.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(jsonLoginRequest.toString()));
服务器处理代码为:
@POST
@Path("logins")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response generateToken(@Context HttpServletRequest request) {
if (request != null) {
User user;
DBHandshaker handshaker = DBHandshaker.getInstance();
user = handshaker.logUser(request.getParameter("username"), request.getParameter("password"));
if (user != null) {
StringUtil stringUtil = StringUtil.getInstance();
String tokenString = stringUtil.encryptForToken(user.getUsername(), user.getPassword());
HashMap<String, String> tokenMap = new HashMap<>();
tokenMap.put("token", tokenString);
JSONObject jsonLoginResponse = new JSONObject();
try {
jsonLoginResponse.put("login-token", tokenMap);
} catch (JSONException e) {
e.printStackTrace();
}
return Response.ok(jsonLoginResponse.toString(), MediaType.APPLICATION_JSON).build();
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
}
我的客户响应“捕手”是:
LoginParser loginParser = new LoginParser();
Response response = loginParser.parseRequest(username, password);
boolean isValidLogin = Response.Status.OK.getStatusCode() == response.getStatusInfo().getStatusCode();
if (isValidLogin) {
// Store the current username in the service session
getSession().setAttribute("user", username);
HttpEntity entity = (HttpEntity) response.getEntity();
try {
String retSRc = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(retSRc);
System.out.println(jsonObject);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
// Navigate to main view
getUI().getNavigator().navigateTo(LoginMainView.NAME);//
}
我在 response.getEntity() 上遇到问题,因为它既不是 JSON 也不是 HttpEntity,而是 org.glassfish.jersey.client.HttpUrlConnector。我的错误在哪里?
最佳答案
代替 response.getEntity()
,使用 response.readEntity(String.class)
或 response.readEntity(HttpEntity.class)
.
关于java - Jersey JSON 响应作为 HttpUrlConnector 而不是 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26696880/