swagger-js-codegen api发送错误的请求标头内容类型

时间:2016-08-24 21:11:28

标签: angularjs swagger swagger-2.0

所以我从1.x升级到Swagger 2,我遇到了一个奇怪的问题。我的一个API是将不正确的内容类型注入到标题中,我不知道从哪里来,你可以在下面的SwaggerJSON中看到,DELETE函数甚至说它消耗了application / json,但是CURL(从inspect面板复制) )因为它发送'Content-Type:text / plain; charset = UTF-8'。我已经提供了CREATE函数作为一个粗略的例子来表明,否则类似的apis工作正常。我认为这是swagger-js-codegen的一个问题,因为如果我将相同的请求放入api-docs它工作正常,或者当然是我的Java,或某种方式我的内容类型标题正在设置,但我没有想法如何或在哪里。我错过了什么吗?无论我的JAVA是否声称'consume =“application / json”',API的行为都是相同的。

Swagger JSON

{
  "/api/entities/{id}/labels": {
    "delete": {
      "consumes": [
        "application/json"
      ],
      "operationId": "deleteEntityLabel",
      "parameters": [
        {
          "default": "16_appiniteDev",
          "description": "The id of the entity to be edited",
          "in": "path",
          "name": "id",
          "required": true,
          "type": "string"
        },
        {
          "description": "The label/labels to be deleted",
          "in": "body",
          "name": "labels",
          "required": true,
          "schema": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        }
      ],
      "produces": [
        "application/json"
      ],
      "responses": {
        "200": {
          "description": "OK",
          "schema": {
            "$ref": "#/definitions/ResponseEntity"
          }
        },
        "204": {
          "description": "No Content"
        },
        "401": {
          "description": "Unauthorized"
        },
        "403": {
          "description": "Forbidden"
        }
      },
      "summary": "Deletes Labels for Entities",
      "tags": [
        "entity-resource"
      ]
    },
    "post": {
      "consumes": [
        "application/json"
      ],
      "operationId": "createEntityLabel",
      "parameters": [
        {
          "default": "16_appiniteDev",
          "description": "The id of the entity to be edited",
          "in": "path",
          "name": "id",
          "required": true,
          "type": "string"
        },
        {
          "description": "The array of labels to be set",
          "in": "body",
          "name": "labels",
          "required": true,
          "schema": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        }
      ],
      "produces": [
        "application/json"
      ],
      "responses": {
        "200": {
          "description": "OK",
          "schema": {
            "$ref": "#/definitions/ResponseEntity"
          }
        },
        "201": {
          "description": "Created"
        },
        "401": {
          "description": "Unauthorized"
        },
        "403": {
          "description": "Forbidden"
        },
        "404": {
          "description": "Not Found"
        }
      },
      "summary": "Creates Labels for Entities",
      "tags": [
        "entity-resource"
      ]
    }
  }
}

DELETE
JAVA/SPRING
    /**
     * DELETE /entities/{id}/labels -> delete labels for an entity
     *
     * @param id
     * @param labels
     * @throws ServiceException
     */
    @RequestMapping(value = "/entities/{id}/labels", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @ApiOperation(value = "Deletes Labels for Entities", nickname = "deleteEntityLabel", consumes = "application/json")

    public ResponseEntity deleteLabels(
            @ApiParam(value = "The id of the entity to be edited", required = true, defaultValue = "16_appiniteDev") @PathVariable final String id,
            @ApiParam(value = "The label/labels to be deleted", required = true, defaultValue = "[\"label1\",\"label2\",\"label3\"]") @NotNull final @RequestBody String[] labels

    ) throws ServiceException {
        boolean isAppEntity = false;
        User user = userService.getUserWithAuthorities();
        String[] type = id.split("_");
        if (StringUtils.isNumeric(type[0]) && !type[1].startsWith(type[0])) {
            isAppEntity = true;

        }

        entityService.deleteTags(id, labels, user, isAppEntity);
        Map<String, String> response = new LinkedHashMap<>();
        response.put(Constants.RESPONSE_ENTITY_HEADER_MESSAGE,
                "Labels deleted successfully");
        return new ResponseEntity(response, HttpStatus.OK);
    }

CURL FROM APP
curl 'http://localhost:8080//api/entities/52_QA42/labels?cacheBuster=1472070679337' -X DELETE -H 'Pragma: no-cache' -H 'Origin: http://localhost:8080' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: application/json, text/plain, */*' -H 'Cache-Control: no-cache' -H 'x-auth-token: admin:1472097365429:8e6524e252e2aebb786b7738c44fe385' -H 'Referer: http://localhost:8080/' -H 'Cookie: NG_TRANSLATE_LANG_KEY=%22en%22' -H 'Connection: keep-alive' -H 'DNT: 1' --data-binary '["Bug13124"]' --compressed


CREATE
JAVA/SPRING
    /**
     * POST /entities/{id}/labels -> add labels for a non hadoop entity
     *
     * @param id
     * @param labels
     * @throws ServiceException
     */
    @RequestMapping(value = "/entities/{id}/labels", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @ApiOperation(value = "Creates Labels for Entities", nickname = "createEntityLabel")
    public ResponseEntity addLabels(
            @ApiParam(value = "The id of the entity to be edited", required = true, defaultValue = "16_appiniteDev") @PathVariable final String id,
            @ApiParam(value = "The array of labels to be set", required = true, defaultValue = "[\"label1\",\"label2\",\"label3\"]") @NotNull final @RequestBody String[] labels)
            throws ServiceException {
        boolean isAppEntity = false;
        User user = userService.getUserWithAuthorities();
        String[] type = id.split("_");
        if (StringUtils.isNumeric(type[0]) && !type[1].startsWith(type[0])) {
            isAppEntity = true;

        }

        entityService.addTags(id, labels, user, isAppEntity);
        Map<String, String> response = new LinkedHashMap<>();
        response.put(Constants.RESPONSE_ENTITY_HEADER_MESSAGE,
                "Labels added successfully");
        return new ResponseEntity(response, HttpStatus.OK);
    }

CURL FROM APP
curl 'http://localhost:8080//api/entities/52_QA42/labels?cacheBuster=1472071851544' -H 'Pragma: no-cache' -H 'Origin: http://localhost:8080' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36' -H 'Content-Type: application/json;charset=UTF-8' -H 'Accept: application/json, text/plain, */*' -H 'Cache-Control: no-cache' -H 'x-auth-token: admin:1472097365429:8e6524e252e2aebb786b7738c44fe385' -H 'Referer: http://localhost:8080/' -H 'Cookie: NG_TRANSLATE_LANG_KEY=%22en%22' -H 'Connection: keep-alive' -H 'DNT: 1' --data-binary '["test"]' --compressed

任何想法?

1 个答案:

答案 0 :(得分:1)

我无法确定设置Content-Type的方式或位置,所以我用蛮力的方式解决了这个问题:创建了一个拦截器来强制更改标题内容类型:

.factory('contentInterceptor', function ($rootScope, $q, $location, localStorageService, $cookies) {
    return {
        // Add authorization token to headers
        request: function (config) {
            config.headers = config.headers || {};
            config.headers['Content-Type'] = 'application/json';
            return config;
        }
    };
})

.config(function ($httpProvider) {
    $httpProvider.interceptors.push('contentInterceptor');
});

像魅力一样工作,幸运的是不会影响我的任何其他API,因为它们除了多部分形式之外都需要Application / JSON,但那些显式设置并且不受此拦截器的影响。

**** 更新 *****

我是一个愚蠢的哑巴,并没有意识到我只能将以下内容放入我的小胡子模板中。这是正确的答案。它需要适当的“消耗”和“生成”属性,并确保正在发送正确的标头。

{{#headers}}
    options.headers['{{&name}}'] = {{&value}};
{{/headers}}