我正在使用RestTemplate restTemplate.exchange
方法向端点发送POST请求。我要传递给POST请求的文件中有OAuth Header
和HttpEntity
,除此之外,我还想将request
传递给端点。
我能够成功传递标题和请求,但无法传递包含凭据的Http实体
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
new HttpEntity<>(request, dataRepo.getHeader()), String.class);
我有什么办法可以通过所有三件事
HttpEntity
HttpHeaders
请求
这是我的代码
@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文件中,该文件包含Header
和HttpEntity
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;
}
}
报价问题:
我有什么办法可以通过所有三件事