ProgramingTip

Jersey 클라이언트 : 목록을 쿼리 매개 변수로 추가하는 방법

bestdevel 2020. 10. 21. 21:16
반응형

Jersey 클라이언트 : 목록을 쿼리 매개 변수로 추가하는 방법


쿼리로 나열 변수가있는 GET 서비스 용 Jersey 클라이언트를 만들고 있습니다. 문서 에 따르면 목록을 쿼리 매개 변수로 사용할 수 있습니다 (이 정보는 @QueryParam javadoc에도 있음). 확인하십시오.

일반적으로 Java 유형의 매개 변수는 다음과 가변적이다.

  1. 원시 유형이어야합니다.
  2. 단일 문자열 인수를 허용하는 경우 생성되어야합니다.
  3. 단일 공유 인수를 허용하는 valueOf 또는 fromString이라는 메소드 메소드가 있습니다 (예 : Integer.valueOf (String) 및 java.util.UUID.fromString (String)). 또는
  4. List, Set 또는 SortedSet은 필수입니다. 여기서 T는 위의 2 또는 3을 씁니다. 결과 컬렉션은 읽기 전용입니다.

동일한 이름에 대해 둘 이상의 값을 포함 할 수 있습니다. 이 경우 4) 사용하여 모든 값을 얻을 수 있습니다.

그러나 Jersey 클라이언트를 사용하여 목록 쿼리 변수를 추가하는 방법을 알 수 없습니다.

대체 솔루션은 다음과 가변적입니다.

  1. GET 대신 POST를 사용하십시오.
  2. 목록을 JSON 공유로 변환하고 서비스에 전달합니다.

서비스에 대한 적절한 HTTP 동사가 GET이기 때문에 첫 번째는 좋지 않습니다. 데이터 검색 작업입니다.

두 번째는 당신이 나를 도울 수있는 것은 나의 선택이 될 것입니다. :)

또한 서비스를 개발 중 필요에 따라 방송 수 있습니다.

감사합니다!

최신 정보

클라이언트 코드 (json 사용)

Client client = Client.create();

WebResource webResource = client.resource(uri.toString());

SearchWrapper sw = new SearchWrapper(termo, pagina, ordenacao, hits, SEARCH_VIEW, navegadores);

MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("user", user.toUpperCase()); 
params.add("searchWrapperAsJSON", (new Gson()).toJson(sw));

ClientResponse clientResponse = webResource .path("/listar")
                                            .queryParams(params)
                                            .header(HttpHeaders.AUTHORIZATION, AuthenticationHelper.getBasicAuthHeader())
                                            .get(ClientResponse.class);

SearchResultWrapper busca = clientResponse.getEntity(new GenericType<SearchResultWrapper>() {});

@GET 지원 목록을 지원

설정 :
Java : 1.7
Jersey 버전 : 1.9

자원

@Path("/v1/test")

하위 리소스 :

// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
    log.info("receieved list of size="+list.size());
    return Response.ok().build();
}

저지 테스트 케이스

@Test
public void testReceiveListOfStrings() throws Exception {
    WebResource webResource = resource();
    ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
            .queryParam("list", "one")
            .queryParam("list", "two")
            .queryParam("list", "three")
            .get(ClientResponse.class);
    Assert.assertEquals(200, responseMsg.getStatus());
}

간단한 것보다 간소화 된 제안 제안 요청 본문과 함께 POST를 사용하거나 전체 목록을 전달하는 것이 좋습니다. 그러나 간단한 간단한 절차를 사용하는 경우 각 값을 요청 URL에 추가하기 만하면 Jersey 가이를 역화합니다. 따라서 다음 예제 엔드 포인트가 제공됩니다.

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {
        super();
    }

    @GET
    @Path("/withlist")
    @Produces(MediaType.TEXT_PLAIN)
    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();
    }
}

클라이언트는 해당하는 요청을 보냅니다.

GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye

어떤 초래 inputList값 '안녕하세요', '스테이'와 '안녕'을 포함 직렬화 복원되는


언급 된 한 대체 솔루션에 대해 동의합니다.

1. Use POST instead of GET;
2. Transform the List into a JSON string and pass it to the service.

당신이 추가 할 수있는 것은 사실 ListMultiValuedMap때문에 IMPL 클래스는 클래스 MultivaluedMapImpl키와 값을 수용 할 능력을 가지고 있습니다. 다음 그림에 나와 있습니다.

여기에 이미지 설명 입력

여전히 코드를 따르는 것보다 그 일을하고 싶습니다.

컨트롤러 클래스

package net.yogesh.test;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;

@Path("test")
public class TestController {
       @Path("testMethod")
       @GET
       @Produces("application/text")
       public String save(
               @QueryParam("list") List<String> list) {

           return  new Gson().toJson(list) ;
       }
}

클라이언트 클래스

package net.yogesh.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class Client {
    public static void main(String[] args) {
        String op = doGet("http://localhost:8080/JerseyTest/rest/test/testMethod");
        System.out.println(op);
    }

    private static String doGet(String url){
        List<String> list = new ArrayList<String>();
        list = Arrays.asList(new String[]{"string1,string2,string3"});

        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        String lst = (list.toString()).substring(1, list.toString().length()-1);
        params.add("list", lst);

        ClientConfig config = new DefaultClientConfig();
        com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
        WebResource resource = client.resource(url);

        ClientResponse response = resource.queryParams(params).type("application/x-www-form-urlencoded").get(ClientResponse.class);
        String en = response.getEntity(String.class);
        return en;
    }
}

이것이 당신을 도울 수 있기를 바랍니다.


JSON 쿼리 매개 변수를 사용 GET 요청

package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientGET {

    public static void main(String[] args) {
        try {               

            String BASE_URI="http://vaquarkhan.net:8080/khanWeb";               
            Client client = Client.create();    
            WebResource webResource = client.resource(BASE_URI);

            ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);

            /*if (response.getStatus() != 200) {
               throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
            }
*/
            String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
            //String output = response.getEntity(String.class);

            System.out.println("Output from Server .... \n");
            System.out.println(output);                         

        } catch (Exception e) {

            e.printStackTrace();    
        }    
    }    
}

요청 게시 :

package com.rest.jersey.jerseyclient;

import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class JerseyClientPOST {

    public static void main(String[] args) {
        try {

            KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");                      

            ClientConfig clientConfig = new DefaultClientConfig();

            clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

            Client client = Client.create(clientConfig);

               // final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
               // client.addFilter(authFilter);
               // client.addFilter(new LoggingFilter());

            //
            WebResource webResource = client
                    .resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");

              ClientResponse response = webResource.accept("application/json")
                .type("application/json").put(ClientResponse.class, khanDTOInput);


            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
            }

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

            System.out.println("Server response .... \n");
            System.out.println(output);

        } catch (Exception e) {

            e.printStackTrace();

        }    
    }    
}

참고 URL : https://stackoverflow.com/questions/13750010/jersey-client-how-to-add-a-list-as-query-parameter

반응형