如何在 javax.ws.rs.core.Response 中设置响应正文

How set Response body in javax.ws.rs.core.Response

有一个 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);
    } 

}  

这里message是我需要设置的。但是我尝试了几种方法。没有工作他们中的任何一个。

以下解决方案之一应该可以解决问题:

return Response.ok(entity).build();
return Response.ok().entity(entity).build();

有关详细信息,请查看 Response and Response.ResponseBuilder 类 文档。

提示:在Response.ResponseBuilder API you might find some useful methods that allow you to add information related to cache, cookies and headers到HTTP响应中。