尝试进行JSON调用时出现415(不支持的媒体类型)错误

时间:2014-06-11 06:26:50

标签: java javascript json spring resteasy

我正在休息时收到此错误。

GET localhost:8082/abc/rest/hello/world 415 (Unsupported Media Type) jquery-    1.11.0.min.js:4
    n.ajaxTransport.send jquery-1.11.0.min.js:4
    n.extend.ajax jquery-1.11.0.min.js:4
    n.each.n.(anonymous function) jquery-1.11.0.min.js:4
    n.extend.getJSON jquery-1.11.0.min.js:4
    getExcelOutput utility.js:6
    (anonymous function)

这是我的javascript函数(#showdata是div的id,我将显示字符串数据):

function getExcelOutput() {
    $.getJSON("/abc/rest/hello/world", function(data) { 
         $('#showdata').html("<p>item1="+data.val()+"</p>");
     });
    }

这是调用服务的java代码(另一个java代码)

@RequestScoped
public class ABCServiceImpl implements BasicService {

    @GET
    @Path("/hello/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    public String hello(@PathParam("name") String name) {
        return generateProxy().hello(name);
    }

    private BasicService generateProxy() {
        return ProxyFactory.create(BasicService.class, "http://localhost:9090/service/lesson1/");
    }

}

服务端代码功能:

    @GET
    @Path("hello/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    public String hello(String name)
    {
        return "Hello " + name + excelReader.excelReading(); 
    } 

2 个答案:

答案 0 :(得分:1)

添加&#34;内容类型:application / json&#34;和&#34;接受:application / json&#34;在REST客户端标题部分

由于您的代码正在尝试使用JSON,您确定已在Jackson注册了该课程吗?默认情况下,JAXB将启用XML的序列化,但对于JSON,您需要包含Jackson。

此处有更多信息:https://jersey.java.net/documentation/latest/media.html#json.jackson

答案 1 :(得分:0)

这样做,它可以通过添加此过滤器来实现:

package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

/**
 * 
 * @author Toni
 *
 */
@Component
public class SimpleCORSFilter implements Filter {

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    chain.doFilter(req, res);
  }

  public void init(FilterConfig filterConfig) {}

  public void destroy() {}

}