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

415 (Unsupported Media Type) error while trying to make a JSON call

本文关键字:JSON 调用 出错 不支持 媒体 类型      更新时间:2023-09-26

我得到这个错误,而我正在进行休息呼叫。

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(); 
    } 

在REST客户端报头部分添加"Content-Type: application/json"answers"Accept: application/json"

既然你的代码是试图与JSON工作,你确定你已经在杰克逊注册类吗?默认情况下,JAXB将启用XML之间的序列化,但是对于JSON,您需要包含Jackson。

更多信息在这里:https://jersey.java.net/documentation/latest/media.html#json.jackson

这样做,它将通过添加以下过滤器来工作:

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() {}
}