Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4018810
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T10:01:43+00:00 2026-05-20T10:01:43+00:00

I need to make a Rest POST to a service that returns either a

  • 0

I need to make a Rest POST to a service that returns either a <job/> or an <exception/> and always status code 200. (lame 3rd party product!).

I have code like:

Job job = getRestTemplate().postForObject(url, postData, Job.class);

And my applicationContext.xml looks like:

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
    <constructor-arg ref="httpClientFactory"/>

    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
                <property name="marshaller" ref="jaxbMarshaller"/>
                <property name="unmarshaller" ref="jaxbMarshaller"/>
            </bean>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        </list>
    </property>
</bean>

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list>
            <value>domain.fullspec.Job</value>
            <value>domain.fullspec.Exception</value>
        </list>
    </property>
</bean>

When I try to make this call and the service fails, I get:

 Failed to convert value of type 'domain.fullspec.Exception' to required type 'domain.fullspec.Job'

In the postForObject() call, I am asking for a Job.class and not getting one and it is getting upset.

I am thinking I need to be able to do something along the lines of:

Object o = getRestTemplate().postForObject(url, postData, Object.class);
if (o instanceof Job.class) {
   ...
else if (o instanceof Exception.class) {
}

But this doesnt work because then JAXB complains that it doesnt know how to marshal to Object.class – not surprisingly.

I have attempted to create subclass of MarshallingHttpMessageConverter and override readFromSource()

protected Object readFromSource(Class clazz, HttpHeaders headers, Source source) {

    Object o = null;
    try {
        o = super.readFromSource(clazz, headers, source);
    } catch (Exception e) {
        try {
            o = super.readFromSource(MyCustomException.class, headers, source);
        } catch (IOException e1) {
            log.info("Failed readFromSource "+e);
        }
    }

    return o;
}

Unfortunately, this doesnt work because the underlying inputstream inside source has been closed by the time I retry it.

Any suggestions gratefully received,

Tom

UPDATE: I have got this to work by taking a copy of the inputStream

protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) {
    InputStream is = ((StreamSource) source).getInputStream();

    // Take a copy of the input stream so we can use it for initial JAXB conversion
    // and if that fails, we can try to convert to Exception
    CopyInputStream copyInputStream = new CopyInputStream(is);

    // input stream in source is empty now, so reset using copy
    ((StreamSource) source).setInputStream(copyInputStream.getCopy());

    Object o = null;
    try {
        o = super.readFromSource(clazz, headers, source);
      // we have failed to unmarshal to 'clazz' - assume it is <exception> and unmarshal to MyCustomException

    } catch (Exception e) {
        try {

            // reset input stream using copy
            ((StreamSource) source).setInputStream(copyInputStream.getCopy());
            o = super.readFromSource(MyCustomException.class, headers, source);

        } catch (IOException e1) {
            e1.printStackTrace();  
        }
        e.printStackTrace();
    }
    return o;

}

CopyInputStream is taken from http://www.velocityreviews.com/forums/t143479-how-to-make-a-copy-of-inputstream-object.html, i’ll paste it here.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class CopyInputStream
{
private InputStream _is;
private ByteArrayOutputStream _copy = new ByteArrayOutputStream();

/**
 * 
 */
public CopyInputStream(InputStream is)
{
    _is = is;

    try
    {
        copy();
    }
    catch(IOException ex)
    {
        // do nothing
    }
}

private int copy() throws IOException
{
    int read = 0;
    int chunk = 0;
    byte[] data = new byte[256];

    while(-1 != (chunk = _is.read(data)))
    {
        read += data.length;
        _copy.write(data, 0, chunk);
    }

    return read;
}

public InputStream getCopy()
{
    return (InputStream)new ByteArrayInputStream(_copy.toByteArray());
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T10:01:44+00:00Added an answer on May 20, 2026 at 10:01 am

    @Tom: I don’t think creating a custom MarshallingHttpMessageConverter will do you any good. The built-in converter is returning you the right class (Exception class) when the service fails, but it is the RestTemplate that doesn’t know how to return Exception class to the callee because you have specified the response type as Job class.

    I read the RestTemplate source code, and you are currently calling this API:-

    public <T> T postForObject(URI url, Object request, Class<T> responseType) throws RestClientException {
        HttpEntityRequestCallback requestCallback = new HttpEntityRequestCallback(request, responseType);
        HttpMessageConverterExtractor<T> responseExtractor =
                new HttpMessageConverterExtractor<T>(responseType, getMessageConverters());
        return execute(url, HttpMethod.POST, requestCallback, responseExtractor);
    }
    

    As you can see, it returns type T based on your response type. What you probably need to do is to subclass RestTemplate and add a new postForObject() API that returns an Object instead of type T so that you can perform the instanceof check on the returned object.

    UPDATE

    I have been thinking about the solution for this problem, instead of using the built-in RestTemplate, why not write it yourself? I think that is better than subclassing RestTemplate to add a new method.

    Here’s my example… granted, I didn’t test this code but it should give you an idea:-

    // reuse the same marshaller wired in RestTemplate
    @Autowired
    private Jaxb2Marshaller jaxb2Marshaller;
    
    public Object genericPost(String url) {
        // using Commons HttpClient
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
    
        // add your data here
        method.addParameter("data", "your-data");
    
        try {
            int returnCode = client.executeMethod(method);
    
            // status code is 200
            if (returnCode == HttpStatus.SC_OK) {
                // using Commons IO to convert inputstream to string
                String xml = IOUtil.toString(method.getResponseBodyAsStream());
                return jaxb2Marshaller.unmarshal(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));
            }
            else {
                // handle error
            }
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
            method.releaseConnection();
        }
    
        return null;
    }
    

    If there are circumstances where you want to reuse some of the APIs from RestTemplate, you can build an adapter that wraps your custom implementation and reuse RestTemplate APIs without actually exposing RestTemplate APIs all over your code.

    For example, you can create an adapter interface, like this:-

    public interface MyRestTemplateAdapter {
        Object genericPost(String url);
    
        // same signature from RestTemplate that you want to reuse
        <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables);
    }
    

    The concrete custom rest template looks something like this:-

    public class MyRestTemplateAdapterImpl implements MyRestTemplateAdapter {
        @Autowired
        private RestTemplate    restTemplate;
    
        @Autowired
        private Jaxb2Marshaller jaxb2Marshaller;
    
        public Object genericPost(String url) {
            // code from above
        }
    
        public <T> T postForObject(String url, Object request, Class<T> responseType, Object... uriVariables) {
            return restTemplate.postForObject(url, request, responseType);
        }
    }
    

    I still think this approach is much cleaner than subclassing RestTemplate and you have more control on how you want to handle the results from the web service calls.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to make POST request to REST web-service with header params and form
I need to make a request to an API, using REST (POST method) in
I have a Spring MVC and Resteasy based REST service that i need to
In part of my PHP application, I need to make an REST style API
I need to make an AJAX request from a website to a REST web
Using restlet, I want to make a post to android's c2dm service. I have
I'm working on a PHP script that needs to communicate with a service REST
I wrote some wcf interface ( REST ) that need to be called from
I trying to make http - post call. The server that i send him
I am using a REST API with a cloud service. Using Powershell, I need

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.