Jersey JSON响应为HttpUrlConnector而不是JSON

时间:2014-11-02 07:07:37

标签: java json rest jax-rs jersey-2.0

我正在尝试使用Jersey 2.13作为服务器进行小型REST服务,将Vaadin 7.3.3作为“客户端”,但想法是请求可以来自任何地方(不仅仅是Vaadin,这就是我不喜欢的原因)在请求时使用bean。假设用户已经注册,请求只检查他是否存在,并返回令牌。我有一个POST网址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。我的错误在哪里?

2 个答案:

答案 0 :(得分:6)

而不是response.getEntity(),请使用response.readEntity(String.class)response.readEntity(HttpEntity.class)

答案 1 :(得分:2)

客户端处理代码

package net.test;

import java.util.HashMap;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class Consumer {
    public static void main(String[] args) {
        Client client = Client.create();
        ClientResponse clientResponse = null;

        User u = new User();
        u.setUsername("hello");
        u.setPassword("hello");
        WebResource webResource = client
            .resource("http://localhost:8080/"+appName"+/logins");
        HashMap<String, String> userMap = new HashMap<String, String>();
        userMap.put("username", u.getUsername());
        userMap.put("password", u.getPassword());
        // JSON logins request!
        JSONObject jsonLoginRequest = new JSONObject();
        try {
            jsonLoginRequest.put("login-request", userMap);
            System.out.println(jsonLoginRequest.get("login-request"));
            System.out.println(jsonLoginRequest.getJSONObject("login-request")
                .get("username"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
       // POST Operation
       clientResponse = webResource.post(ClientResponse.class,
            jsonLoginRequest);
       System.out.println(jsonLoginRequest);
    // Send the return value in object
       String result = clientResponse.getEntity(String.class);
       System.out.println(result);
 }
}

服务器处理代码

package net.test;
//Server Processing code
import java.util.HashMap;
import java.util.Random;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

@Path("/")
public class Producer {
   @POST
   @Path("logins")
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces(MediaType.APPLICATION_JSON)
   public Response generateToken(String objInputData) {

    JSONObject jsonObject = null;
    User user = null;
    String username = null;
    String password = null;
    try {
        jsonObject = new JSONObject(objInputData);
        user = new User();
        username = jsonObject.getJSONObject("login-request")
                .get("username").toString();
        password = jsonObject.getJSONObject("login-request")
                .get("password").toString();
        // Your business logic goes here
        // DBHandshaker handshaker = DBHandshaker.getInstance();
        // user = handshaker.logUser(username, password);
        System.out.println(username+password);
        if (user != null) {
            // write your logic to generate token
            // StringUtil stringUtil = StringUtil.getInstance();
            // String tokenString =
            // stringUtil.encryptForToken(user.getUsername(),
            // user.getPassword());
            // dummy string to test
            String tokenString = "Helllllllllgjdkg";

            HashMap<String, String> tokenMap = new HashMap<String, String>();
            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();
        }
    } catch (Exception e1) {
        return Response.status(Response.Status.NO_CONTENT).build();
    }
}
}

获得回复后编写捕手逻辑

希望这个答案对你有所帮助