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

19

需要实现一个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是我需要设置的内容。但是我尝试了几种方法,都没有成功。

1个回答

39

3
好的,我会尽力为您翻译。以下是需要翻译的内容:是的。 return Response.ok(message).build() 对我有用。此外,return Response.ok().entity(message).build() 不起作用。无论如何,感谢并接受答案。 - GPrathap
3
Response.ok(message).build() 将返回一个 200 状态码,我们能否对 BAD_REQUEST 做类似的事情,也就是添加自定义消息? - prime
3
@prime return Response.status(Response.Status.BAD_REQUEST).entity(entity).build(); @prime 返回Response.status(Response.Status.BAD_REQUEST).entity(entity).build(); - cassiomolin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接