Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass InputStream to REST service POST method

How to pass InputStream to createParcel() method using Java REST client? How to call POST request using POSTMAN?

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
public int createParcel(InputStream is) {
    int awbNo = 0;
    try {
        ParcelInfo parcelInfo = null;
        parcelInfo = buildParcelInfo(is);
        awbNo = index.incrementAndGet();
        parcelInfo.setAwbNo(awbNo);
        parcelInfo.setStatus("new");
        parcelDataMap.put(awbNo, parcelInfo);
   } catch(Exception ex) {
        logger.error("Getting some exception for creating parcel : "+ex.getMessage(), ex);
   }
   return awbNo;
}

@GET
@Produces(MediaType.APPLICATION_XML)
public StreamingOutput getParcelInfo(@QueryParam("awbNo") int awbNo) {
    ParcelInfo parcelInfo = null;
    String xml = null;
    parcelInfo = parcelDataMap.get(awbNo);

    if (parcelInfo != null) {
        xml = convert(parcelInfo);
    }
    return new ParcelInfoWriter(xml);
}
like image 626
vijay velaga Avatar asked Oct 25 '16 06:10

vijay velaga


1 Answers

Because you are not consuming structured data but rather a raw InputStream, you first remove the @Consumes annotation; so your resource method should be:

@POST
@Produces(MediaType.TEXT_PLAIN)
public int createParcel(InputStream is) {
    int awbNo = 0;
    try {
        ParcelInfo parcelInfo = null;
        parcelInfo = buildParcelInfo(is);
        // the rest of your code here
   }catch(Exception ex) {
        // catch specific exception instead of `Exception`
   }
   return awbNo;
}

Now use Postman to call your resource. The content body of your request can be any conent (in my example it is XML but you can send anything you like). Look at the screenshot below how to set the request correctly:

enter image description here

Execuse me for the drawing :-)

like image 58
ujulu Avatar answered Nov 15 '22 04:11

ujulu