junit Postman中的Sping Boot MultiValueMap参数

yqkkidmi  于 9个月前  发布在  Postman
关注(0)|答案(3)|浏览(155)

我在Sping Boot 中实现了OAuth2。在JUnit中测试时它工作得很好,但是当我在Postman中尝试API时,总是得到未经授权的结果。
JUnit中的测试函数:

private String obtainAccessToken(String username, String password) throws Exception {
    final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("client_id", CLIENT_ID);
    params.add("username", username);
    params.add("password", password);

    ResultActions result = mockMvc.perform(post("/oauth/token")
            .params(params)
            .with(httpBasic(CLIENT_ID, CLIENT_SECRET))
            .accept(CONTENT_TYPE))
            .andExpect(status().isOk())
            .andExpect(content().contentType(CONTENT_TYPE));

    String resultString = result.andReturn().getResponse().getContentAsString();

    JacksonJsonParser jsonParser = new JacksonJsonParser();
    return jsonParser.parseMap(resultString).get("access_token").toString();
}

我在Postman中尝试了以下API:
POST类型http://localhost:8080/oauth/token,内容类型application/json在正文部分中,我选择了raw和JSON:

{
    "grant_type":"password",
    "client_id":"clientIdPassword",
    "username":"a",
    "password":"a"
}

401未授权然后我也这样尝试:
内容类型为application/jsonhttp://localhost:8080/oauth/token?grant_type=password&client_id=clientIdPassword&username=a&password=a的帖子类型。401 Unauthorized未授权
我的问题是如何将MultiValueMap设置为Postman中的参数?

e5nszbig

e5nszbig1#

你应该使用postman的authorization选项卡来发送auth标题沿着你喜欢的请求体。PFA样本image

qmb5sa22

qmb5sa222#

当您通过POSTMAN工具发送请求时,选择HTTP方法的类型(POST,PUT,HTTP),然后选择“Body”选项卡中的“raw”选项,然后只需将Map的JSON添加其中。确保您在“Headers”中选择了“Content-type”作为“application/json”。

v9tzhpje

v9tzhpje3#

你应该在body下的form-data中添加这些参数值

相关问题