如何在javax.ws.rs.core.Response中设置Response body

GPr*_*hap 10 java rest web-services jax-rs java-ee

需要实现的REST API端点用于获取一些信息并将后端请求发送到另一个服务器,来自后端服务器的响应必须设置为最终响应.我的问题是如何在javax.ws.rs.core.Response中设置响应体?

@Path("analytics")
@GET
@Produces("application/json")
public Response getDeviceStats(@QueryParam("deviceType") String deviceType,
                               @QueryParam("deviceIdentifier") String deviceIdentifier,
                               @QueryParam("username") String user, @QueryParam("from") long from,
                               @QueryParam("to") long to) {

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContexts.custom()
                .loadTrustMaterial(new File(getClientTrustStoretFilePath()), "password## Heading ##".toCharArray(),
                        new TrustSelfSignedStrategy())
                .build();
    } catch (NoSuchAlgorithmException e) {
        log.error(e);
    } catch (KeyManagementException e) {
        log.error(e);
    } catch (KeyStoreException e) {
        log.error(e);
    } catch (CertificateException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslcontext,
            new String[] { "TLSv1" },
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();
    HttpResponse response = null;
    try {
        HttpGet httpget = new HttpGet(URL);
        httpget.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
        httpget.addHeader("content-type", "application/json");
        response = httpclient.execute(httpget);
        String message = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (ClientProtocolException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    } 

}  
Run Code Online (Sandbox Code Playgroud)

这里的消息是我需要设置的消息.但我尝试了几种方法.没有工作任何一个.

cas*_*lin 23

以下解决方案之一应该做到这一点:

return Response.ok(entity).build();
Run Code Online (Sandbox Code Playgroud)
return Response.ok().entity(entity).build();
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看ResponseResponse.ResponseBuilder类文档.

提示:在Response.ResponseBuilderAPI中,您可能会找到一些有用的方法,允许您将与缓存,cookie标头相关的信息添加到HTTP响应中.

  • 是.`return Response.ok(message).build()`对我有用.还``返回Response.ok().entity(message).build()`不起作用.无论如何,谢谢和加入答案 (3认同)
  • @prime `返回 Response.status(Response.Status.BAD_REQUEST).entity(entity).build();` (3认同)
  • Response.ok(message).build() 将返回 200,我们是否也可以对 BAD_REQUEST 做一些相同的事情。我的意思是添加自定义消息。 (2认同)