简体   繁体   中英

How to retrieve List <String> from HttpResponse object in Java

I am new to this kind of coding where in I have to send a collection of String ie, List from a Spring controller of different web app. So my questions are

  1. How should I return the Response which consists of List from a controller? Does the below code works fine? Below is my controller code where I will be returning List<String> .

     @RequestMapping(value = "getMyBookingsXmlList", method = RequestMethod.GET) public @ResponseBody List<String> getMyBookingsXmlList() { return mbXmlImpl.getMyBookingsDetailsXmlList(); } 
  2. In the client side how should I have to retrieve the List<String> which was sent from the above controller method ? Below is the code which I am trying to do but I have no clue as of how to do.

     HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("URL"); HttpResponse httpResponse = httpclient.execute(httpGet); InputStream is = httpResponse.getEntity().getContent(); StringBuffer buffer = new StringBuffer(); byte [] b = new byte [1024]; for (int n ; (n = is.read(b)) != -1 ;) buffer.append(new String(b, 0, n)); 

After this I don't have a clue what to do....

The easiest solution to consume your Rest service with a java client is to use Spring RestTemplate . I would suggest you wrap your List<String> in another class and return that from your controller:

public class BookingList  {
    private List<String> booking;
    // getters and setters
}

With this your client code will be very simple:

BookingList bookingList = restTemplate.getForObject("http://yoururl", BookingList.class, Collections.emptyMap() ) ;

If you want to continue to keep List<String> as return type, then the client code will look like this:

    ResponseEntity<List<String>> bookingListEntity = restTemplate.exchange("http://yoururl", HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {}, Collections.emptyMap() ) ;
    if (bookingListEntity.getStatusCode() == HttpStatus.OK) {
        List<String> bookingList = bookingListEntity.getBody();
    }

If you are using the jstl you can iterate it through the for-each as

 <c:forEach items="${Name_of_RequestAttribute}" var="ite">
  <option value="${ite.Name_of_RequestAttribute}">${ite.Name_of_RequestAttribute}</option>
 </c:forEach>

Hope this helps!!

I think a better way would be to have a RESTFul webservice in your application that provides the BookingXml.

In case you are planning to expose your Existing Controller code as a Rest Webservice, you could use RestTemplate as explained in this example to make the web service calls.

Other resources you can refer to : http://java.dzone.com/articles/how-use-spring-resttemplate-0 http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch18s03.html

To be specific, in your case you could use this code example :

Controller :

@Controller
@RequestMapping("/help")
public class HelpController {

    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(HelpController.class);

    @RequestMapping("/method")
    public @ResponseBody String[] greeting() {
        return new String[] { "Hello", "world" };
    }
}

Client Code :

public class Client {

    public static void main(final String[] args) {
        final RestTemplate restTemplate = new RestTemplate();
        try {

            final String[] data = restTemplate.getForObject("http://localhost:8080/appname/help/method",
                    String[].class);
            System.out.println(Arrays.toString(data));
        }
        catch (final Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

In case authentication is needed there are 2 ways to pass user credentials when using RestTemplate :

  1. Create your RestTemplate object using this example :

     HttpClient client = new HttpClient(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("your_user","your_password"); client.getState().setCredentials(new AuthScope("thehost", 9090, AuthScope.ANY_REALM), credentials); CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client); RestTemplate template = new RestTemplate(commons); 
  2. Or same can be done using Spring configuraitons as mentioned in this answer : https://stackoverflow.com/a/9067922/1898397

How about this solution?

...
ResponseEntity<MyObject[]> response = 
restTemplate.getForEntity(uribuilder.build().encode().toUri(), 
MyObject[].class);
return Arrays.asList(response.getBody());

Where MyObject can be anything, even String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM