Title

Wednesday, 21 January 2015

How to retrieve List from HttpResponse object in Java


I am new to this kind of coding where in I have to send a collection of String i.e., 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....

Answer

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!!

Answer2

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 (responseEntity.getStatusCode() == HttpStatus.OK) {   List<String> bookingList = responseEntity.getBody();   }
Answer3

Guys I tried with Spring RestTemplate. But later on I found out that I have to do a lot of code change in the existing project. So here what I am trying to do from the client app.

HttpPost httpPost = new HttpPost("URL");  httpPost.setHeader("Cookie", head[0].getValue());  httpPost.setHeader("Content-Type", "application/json");  HttpResponse httpResponse = httpclient.execute(httpPost);

When debugged it, the httpRespone instance has the following content.

HTTP/1.1 200 OK [Server: Apache-Coyote/1.1, Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Tue, 22 Apr 2014 05:26:41 GMT]

Here is my Server side controller code.

@RequestMapping(value="getMyBookingsXmlList" , method = RequestMethod.POST)  public @ResponseBody List<String> getMyBookingsXmlList( ) {  return mbXmlManager.getMyBookingsDetailsXmlList();  }

Guys please help. I am stuck here.

Answer4

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 : http://stackoverflow.com/a/9067922/1898397

No comments:

Post a Comment