Nice programing

게시 요청에서 JAX-RS 클라이언트의 응답 본문 읽기

nicepro 2020. 11. 29. 12:15
반응형

게시 요청에서 JAX-RS 클라이언트의 응답 본문 읽기


모바일 앱과 웹 서비스 사이에 일종의 프록시가 있기 때문에 게시 요청을 보낼 때 응답에 당황합니다. 상태 200 : OK로 응답을받습니다. 그러나 JSON 응답 본문을 찾거나 추출 할 수 없습니다.

    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.target(WEBSERVICE_BASE_LOCATION + "mobileDevices?operatorCode=KPNSCP");
    String jsonString = "{\"osVersion\":\"4.1\",\"apiLevel\":16,\"devicePlatform\":\"ANDROID\"}";
    Builder builder = webTarget.request();
    Response response = builder.post(Entity.json(jsonString));

JAX-RS를 사용하고 있습니다. 누군가 String서버 응답에서 JSON 본문 ( ) 을 추출하기 위해 몇 가지 힌트를 제공 할 수 있습니까 ?


이 시도:

String output = response.getEntity(String.class);

편집하다

@Martin Spamer 덕분에 Jersey 1.x jar에서만 작동한다고 언급했습니다. Jersey 2.x 사용

String output = response.readEntity(String.class);

jaxrs-ri-2.16에 대한 해결책을 찾았습니다.

String output = response.readEntity(String.class)

예상대로 콘텐츠를 제공합니다.


내 사용 사례의 경우 Glassfish Jersey Client Response Object를 모의 할 수 없음 질문에 설명 된대로 다음 오류 메시지로 인해 실패한 서버 측 단위 테스트를 작성했기 때문에 이전 답변 중 어느 것도 작동하지 않았습니다 .

java.lang.IllegalStateException: Method not supported on an outbound message.
at org.glassfish.jersey.message.internal.OutboundJaxrsResponse.readEntity(OutboundJaxrsResponse.java:145)
at ...

이 예외는 다음 코드 줄에서 발생했습니다.

String actJsonBody = actResponse.readEntity(String.class);

수정 사항은 문제 코드 줄을 다음과 같이 바꾸는 것입니다.

String actJsonBody = (String) actResponse.getEntity();

나는 또한 readEntity. getEntity그것은 단지 a를 반환 ByteInputStream하고 본문의 내용을 반환 하지 않기 때문에 프로덕션 코드에서 사용할 수 없으며 단위 테스트에서만 히트하는 프로덕션 코드를 추가 할 방법이 없습니다.

내 해결책은 응답을 만든 다음 Mockito 스파이를 사용하여 readEntity방법 을 모의하는 것입니다.

Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);

when(mockResponse.readEntity(String.class)옵션은 동일한 IllegalStateException.

도움이 되었기를 바랍니다!


문서에 따르면 Jax rs 2.0의 getEntity 메소드는 InputStream을 반환합니다. JSON 형식을 사용하여 InputStream을 String으로 변환해야하는 경우 두 형식을 캐스트해야합니다. 예를 들어 제 경우에는 다음 방법을 구현했습니다.

    private String processResponse(Response response) {
    if (response.getEntity() != null) {
        try {
            InputStream salida = (InputStream) response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(salida, writer, "UTF-8");
            return writer.toString();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

이 방법을 구현 한 이유. 많은 개발자들이 다음 방법을 사용하는 jaxrs의 버전과 동일한 문제를 가지고있는 다른 블로그를 읽었 기 때문에

String output = response.readEntity(String.class)

String output = response.getEntity(String.class)

첫 번째는 com.sun.jersey 라이브러리의 jersey-client를 사용하여 작동하고 두 번째는 org.glassfish.jersey.core의 jersey-client를 사용하여 발견되었습니다.

이것은 나에게 제시된 오류입니다. org.glassfish.jersey.client.internal.HttpUrlConnector $ 2를 java.lang.String으로 캐스팅 할 수 없습니다.

다음 maven 종속성을 사용합니다.

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

What I do not know is why the readEntity method does not work.I hope you can use the solution.

Carlos Cepeda


Realizing the revision of the code I found the cause of why the reading method did not work for me. The problem was that one of the dependencies that my project used jersey 1.x. Update the version, adjust the client and it works.

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

Regards

Carlos Cepeda

참고URL : https://stackoverflow.com/questions/18086621/read-response-body-in-jax-rs-client-from-a-post-request

반응형