2012-03-25 37 views
2

我正在使用RESTEasy,更具體地說,他們的框架的客戶端。REST服務返回錯誤的內容類型和解組

我打電話給我返回一些JSON代碼的第三方Web服務。

但是,由於一些很好的原因,他們的響應中的內容類型是「text/javascript」。

我該如何告訴RESTEasy它應該使用JSON提供程序(解組用於「text/javascript」內容類型?

這可能嗎?

我的代碼:

public interface XClient { 

@GET 
@Produces("application/json") 
@Path("/api/x.json") 
public Movie getMovieInformation(
     @QueryParam("q") String title); 
} 

什麼的解決辦法是這樣的:

public interface XClient { 

@GET 
@Produces("text/javascript") 
// Tell somehow to use json provider despite the produces annotation 
@Path("/api/x.json") 
public Movie getMovieInformation(
     @QueryParam("q") String title); 
} 

回答

0

我的時間不多了,所以這並獲得成功對我來說。我標誌着從服務器字符串的響應,我已經手動傑克遜處理解組:

public interface XClient { 

@GET 
@Path("/api/x.json") 
@Produces(MediaType.APPLICATION_JSON) 
public String getMovieInformation(
     @QueryParam("q") String title, 

} 

,並在我的REST調用:

MovieRESTAPIClient client = ProxyFactory.create(XClient.class,"http://api.xxx.com"); 
String json_string = client.getMovieInformation("taken"); 

ObjectMapper om = new ObjectMapper(); 
Movie movie = null; 
try { 
    movie = om.readValue(json_string, Movie.class); 
} catch (JsonParseException e) { 
myLogger.severe(e.toString()); 
e.printStackTrace(); 
} catch (JsonMappingException e) { 
myLogger.severe(e.toString()); 
    e.printStackTrace(); 
} catch (IOException e) { 
    myLogger.severe(e.toString()); 
    e.printStackTrace(); 
} 

請告知,如果這不是更好的解決方案。但是,這似乎工作。

1

我用它取代傳入的內容類型,像這樣的攔截解決:

this.requestFactory.getSuffixInterceptors().registerInterceptor(
    new MediaTypeInterceptor()); 


static class MediaTypeInterceptor implements ClientExecutionInterceptor { 

    @Override 
    public ClientResponse execute(ClientExecutionContext ctx) throws Exception { 
     ClientResponse response = ctx.proceed(); 
     String contentType = (String) response.getHeaders().getFirst("Content-Type"); 
     if (contentType.startsWith("text/javascript")) { 
      response.getHeaders().putSingle("Content-Type", "application/json"); 
     } 
     return response; 
    } 

} 
+0

但是,這會影響所有傳入的請求? – 2012-08-19 18:14:26

+1

是的,所有的迴應,因爲我們在這裏談論REST客戶端。而且這通常也是你想要的,如果你所說的服務以'text/javascript'返回JSON。無論如何,客戶端無法默認處理這種內容類型。 – pdudits 2012-09-01 10:39:11

相關問題