【问题标题】:Java Spring: Make POST Request with Multiple parametersJava Spring:使用多个参数发出 POST 请求
【发布时间】:2018-10-08 06:37:29
【问题描述】:

我正在尝试在 Spring 中对 REST 调用进行建模: guess {game: 'cdaeaa', guess: 'e' } 输出以下内容: {gameId: 'cdaeaa', word: '____', incorrect: 1, status: 'ACTIVE'}

我基本上需要制作一个需要两个参数的函数。它应该返回游戏数据。游戏类如下:

public class Game {

private final String gameId;
private final String word;
private String guessedWord;
private Set<Character> guessedChars;
private GameStatus status;
private int incorrectGuesses;
private static final int MAX_TRIES = 7;}

但是,当我这样拨打电话时: http://localhost:8080/guess/{asewqd}/{c} (我是否将大括号中的内容放在引号中都没关系。) 我收到以下错误:

//POST
//make guess
@RequestMapping(value = "/guess/{game}/{guess}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Game makeGuess(@PathVariable String game, @PathVariable String guess, HttpSession session) throws GameDoesNotExistException, InvalidCharacterException{
    Game g = getGame(game,session);

    String gameId = g.getId();
    if(gameId.equals(game) && guess.length() > 0) {
        boolean correct = compareWords(guess, g);
        if(!correct){
            g.incIncorrect_guesses();
        }
        g.setStatus();
    }
    else{
        if(!gameId.equals(game)) {
            throw new GameDoesNotExistException(game);
        }
        else{
            throw new InvalidCharacterException(guess);
        }
    }
    g = getGame(game,session);

    return g;
}

【问题讨论】:

  • 你需要调用http://localhost:8080/%project-name%/guess/{asewqd}/{c}而不是http://localhost:8080/guess/{asewqd}/{c},用你的项目名称替换%project-name%。
  • 项目名称是什么意思?
  • 部署的应用程序名称,例如,如果您的项目名为游戏,则 url 将是 localhost:8080/game/guess{asewqd}/{c}
  • pom.xml 中的 artifactId。
  • 那行不通。我收到 404 错误。

标签: java spring rest http spring-boot


【解决方案1】:

您使用浏览器发出请求。浏览器默认使用 GET 方法。

使用经过调整的工具,例如 curl 或 postman 来发出您的 POST 请求。

【讨论】:

    【解决方案2】:

    HTTP 405 表示您尝试使用 HTTP GET 而不是 HTTP POST。

    【讨论】:

    • 但是我有method = RequestMethod.POST
    • 是的,您的方法只接受 POST。但正如您可以阅读错误消息中的最后一行,您正在请求获取。要测试 POST 请求,您应该使用 Postman (getpostman.com)
    • @jdickel 这就是 curl 的情况。 curl "localhost:8080/guess{vcdvnt}/{b}" {"timestamp":"2018-04-27T12:16:49.125+0000","status":405,"error":"Method Not Allowed","message ":"不支持请求方法'GET'","path":"/guess/vcdvnt/b"}
    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2019-12-20
    • 2011-04-28
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2015-03-05
    相关资源
    最近更新 更多