首页 > 解决方案 > 如何将 json 对象发布到 Jersey 客户端的 rest 端点

问题描述

我使用 Jersey 过滤器来获取请求信息,如 sessionID、TimeStamp ......

现在我想将这些值转换为 JSON 对象并发布到另一个休息端点。我尝试使用以下代码,但它不起作用。

private String SessionID;
private String TimeStamp;
private String Path;
private String UserName;

@Override
public void filter(ContainerRequestContext requestContext, 
ContainerResponseContext responseContext) throws IOException {

   System.out.println("response:" + responseContext.getEntity());
  } 

@Override
public void filter(ContainerRequestContext requestContext) throws 
IOException {

  Date requestDate = new Date();
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  TimeStamp = simpleDateFormat.format(requestDate);

  SessionID = requestInfo.getRequestedSessionId();
  UserName = requestInfo.getRemoteUser();
  Path = requestContext.getUriInfo().getPath();

  Map<String, String> map = new HashMap<>();
  map.put("timestamp", TimeStamp);
  map.put("sessionId", SessionID);
  map.put("username", UserName);
  map.put("path", Path);

  JSONObject json = new JSONObject();
  json.putAll(map);
  sendRequest(json);

  System.out.println("========================================");
  System.out.println(json.toJSONString());
  }



private void sendRequest(JSONObject jsonObject) {

  Client client = ClientBuilder.newClient();
  WebTarget target = client.target("http://localhost:8080/test");
  Response res = target.request(MediaType.APPLICATION_JSON).post(Entity.json(jsonObject));
  if (res.getStatus() == 200) {
     System.out.println("ok");
   }
}

我得到了 org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException

/test 只是一个简单的测试服务,它接受 JSON 并返回一个字符串

标签: javarestjerseyjax-rsjersey-client

解决方案


推荐阅读