简体   繁体   中英

Can't read or parse Plain String Response from CXF REST Web Service in Java

A REST Service is implemented correctly in SpringMVC, deployed, and returns the correct result string,

@RestController
public class RESTServiceController {

    @GET
    @Produces("application/json") 
    @RequestMapping("/restUrl")
    public String getResult() {
        JSONObject json = new JSONObject();
        json.put("result", Boolean.TRUE);
    }
}

When testing this Web Service I get the correct output,

{"result":true}

The problem is the caller gets the Response object via CXF, but I don't know how to parse the Response. I don't need a custom object. All I need is the direct string, I just want to see my output string.

String restServiceURI = "http://www.asite.com/restUrl";
WebClient client = WebClient.create(restServiceURI,true);
Response resp = client.get();
//String entity = (String)resp.getEntity; <-- Also tried this to cast to a string

The issue is, the Response length is 0, Status is 302. The getEntity InputStream brings back an EmptyInputStream based on what the debugger shows.

The Response object doesn't have any info that I can see in the debugger.

How do I just get my direct string back? Is there an example?

You are trying mix both Spring Rest and CxF rest. Either use Spring Rest or CXF Rest.

If you want to use Spring Rest as shown below

@Service
public class RESTServiceController {

    @RequestMapping("/restUrl")
    public @ResponseBody MyClass getResult() {
        return myClass;
    }
}

or CXF as shown below.

@Service
public class RESTServiceController {

    @GET
    @Produces("application/json") 
    public MyClass getResult() {
        return myClass;
    }
}

Note: You need not use json conversion explicitly, both Spring Rest and CXF has to feature to convert your object to json string.

However your issue doesn't stop here, I believe you've enabled spring-security, which is sending redirect(302) response, with login page. You can verify response from server by enabling logging in client side.

        WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
        WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());

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