簡體   English   中英

如何解決Jersey + AngularJs中的415不支持的媒體類型錯誤

[英]How to resolve 415 unsupported media type error in Jersey + AngularJs

我正在嘗試從本地計算機讀取Json(文本)文件,並通過Jersey&AngularJs在Web上顯示它。

Web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <display-name>Your REST end Point</display-name>

    <servlet>
        <servlet-name>MyRESTEndPoint</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>


        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>org.itc</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyRESTEndPoint</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

Controller.java

@Path("/")
public class Controller {

    @GET
    @Path("/receive")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject crunchifyREST(int a) throws FileNotFoundException {

        System.out.println("Value received from User is:   "+a);

        String string = "";
        InputStream crunchifyInputStream = new FileInputStream("C:/abc.txt");
        InputStreamReader crunchifyReader = new           InputStreamReader(crunchifyInputStream);
        BufferedReader br = new BufferedReader(crunchifyReader);

        String line;

        try {
                while ((line = br.readLine()) != null) {
                string += line + "\n";
        }
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

       JSONObject jsonObject = null;
       try {
        jsonObject = new JSONObject(string);
       } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return jsonObject;
    }    
}

Controller.js

var app = angular.module('myApp', []); 
app.controller('myController',[ '$scope', '$http', function($scope, $http){

    $scope.myFunc = function() {
    var d=$scope.num;
    $http.get('receive',d ).success(function(dataTable)                   
            {   
                $scope.result = dataTable;

            }).error(function(error)
                {
                console.log(error);
                  });
    }
}]);

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
        <title>Task</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">      </script>
        <script type="text/javascript" src="Controller.js"></script>
    </head>
    <body>
        <div data-ng-app="myApp" data-ng-controller="myController">
            <form id="loginForm" class="form-group" >
                <input type=number data-ng-model="num">
                <button type="submit" class="btn btn-sm btn-success" data-ng-click="myFunc()" >Submit</button>
                <h1>{{ result.name }}</h1>
            </form>
        </div>
    </body>
</html>

我包括以下罐子-

asm-all-3.3.1
jersey-core-1.17.1
jersey-server-1.17.1
jersey-servlet-1.17.1
jersey-json-1.17.1
jersey-bundle-1.17.1
json-20090211

從HTML,我只是將一個虛擬數字作為參數傳遞給$ http。 但是我得到了415種不受支持的媒體類型。 在調試模式下,我可以看到從系統讀取了Json文本文件,並且它無法發送該響應。 有幫助嗎?

首先, @Consumes批注用於指定POST請求的application/contentType標頭,您可以在其中發送請求@Consumes ,因此在GET請求中實際上並不需要它。

其次,似乎您正在嘗試使用Path參數,但沒有為此使用正確的語法。

嘗試您的控制器是這樣的:

@Path("/")
public class Controller {

    @GET
    @Path("/receive/{a}")
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject crunchifyREST(@PathParam("a") int a) throws FileNotFoundException {

        System.out.println("Value received from User is:   "+a);

        String string = "";
        InputStream crunchifyInputStream = new FileInputStream("C:/abc.txt");
        InputStreamReader crunchifyReader = new           InputStreamReader(crunchifyInputStream);
        BufferedReader br = new BufferedReader(crunchifyReader);

        String line;

        try {
                while ((line = br.readLine()) != null) {
                string += line + "\n";
        }
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

       JSONObject jsonObject = null;
       try {
        jsonObject = new JSONObject(string);
       } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return jsonObject;
    }    
}

或者,您可以使用查詢參數。

您需要在請求標頭中將Content-Type設置為application / json。 您的服務器不了解您的要求? 如果可行,請嘗試以下操作。

    var app = angular.module('myApp', []); 
    app.controller('myController',[ '$scope', '$http', function($scope, $http){

         $scope.myFunc = function() {
         var d=$scope.num;
         $http({
           url: 'receive', 
           method: 'GET', 
           data: d, 
           headers: {'Content-Type': 'application/json'}
          }).then(function (dataTable) {
             $scope.result = dataTable;
          }).error(function (error) {
             console.log(error);
          });
        }
    }]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM