如何在POST请求中传递标头和请求正文?

时间:2020-01-25 02:13:42

标签: java spring post resttemplate

我正在使用RestTemplate restTemplate.exchange方法向端点发送POST请求。我有OAuth HeaderHttpEntity在要传递给POST请求的其他文件中,除此之外,我还想将request传递给端点。

我能够成功传递标头和请求,但不能成功传递包含凭据的Http实体

 ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
                new HttpEntity<>(request, dataRepo.getHeader()), String.class);

有什么办法可以让我通过所有三件事

  1. HttpEntity

  2. HttpHeaders

  3. 请求

这是我的代码

@RunWith(MockitoJUnitRunner.class)
@TestPropertySource
public class DataTest {
    @Inject
    private Oauth oauth;

    @Mock
    private DataRepo dataRepo;
    RestTemplate restTemplate = new RestTemplate();

    @Qualifier(OAuth2HttpHeadersBuilder.BEAN_NAME)
    NewHttpHeader headersBuilder;

    @Test
    public void testAddEmployeeSuccess() throws URISyntaxException {

        URI uri = new URI(url);
        Set<String> mockData = Stream.of("A","B").collect(Collectors.toSet());
        String onsString = String.join(",", mockData);

        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("name", onsString);
        JSONObject jsonObject = new JSONObject(requestBody);

        HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), null);

        ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
                new HttpEntity<>(request, dataRepo.getHeader()), String.class);

        Assert.assertEquals(201, result.getStatusCodeValue());
    }

下面的代码在NewHttpHeader.java文件中,该文件包含 HeaderHttpEntity

     private HttpEntity<MultiValueMap<String,String>> getHttpEntity() {
            MultiValueMap<String, String> store = new LinkedMultiValueMap<>();
            store.add( "pas", "password" );
            store.add( "name", config.getVaultServiceAccountName() );
            return new HttpEntity<>( store, getHeader() );
        }


        private HttpHeaders getHeader() {
            HttpHeaders httpHeaders = headersBuilder.build();

            httpHeaders.add( HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType() );
            httpHeaders.add( HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType() );

            return httpHeaders;
        }
    }

1 个答案:

答案 0 :(得分:0)

报价问题:

有什么办法可以让我通过所有三件事

  1. HttpEntity
  2. HttpHeaders
  3. 请求

引用HttpEntity的javadoc:

代表HTTP 请求或响应实体,由标头正文组成。

因此,您的问题的答案是:,您可以通过全部3个,因为第一个只不过是其他两个的组合。

只需合并两个HttpEntity对象。

之前

HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), null);

ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
        new HttpEntity<>(request, dataRepo.getHeader()), String.class);

之后

HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), dataRepo.getHeader());

ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
        request, String.class);