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

问题描述 投票:0回答:1

我正在使用RestTemplate restTemplate.exchange方法向端点发送POST请求。我要传递给POST请求的文件中有OAuth HeaderHttpEntity,除此之外,我还想将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<Flow<String,String>> getHttpEntity() {
            Flow<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;
        }
    }
java spring post resttemplate
1个回答
0
投票

报价问题:

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

© www.soinside.com 2019 - 2024. All rights reserved.