如何将具有 HTTP 基本身份验证的 curl 请求转换为 Spring RestTemplate 请求?



如何将以下curl请求转换为使用 Spring 的 RestTemplate?

curl -u 751061:123456 -i -k -X PUT https://server/api/User/751061 -H 'Content-type: application/xml' -d '<User><state>LOGIN</state><extension>751055</extension></User>'

我尝试按照指南进行操作,但它根本没有提到任何关于身份验证(或XML(的内容。

https://spring.io/guides/gs/consuming-rest/#_make_the_application_executable

API 文档根本没有提到任何关于身份验证的内容。

https://docs.spring.io/spring/docs/5.0.8.BUILD-SNAPSHOT/javadoc-api/org/springframework/web/client/RestTemplate.html

我尝试了以下方法

@PostMapping("/login")
public String login(@RequestParam(name="userId", required=true) String userId,
@RequestParam(name="password", required=true) String password,
@RequestParam(name="extension", required=true) String extension,
HttpSession session,
RestTemplateBuilder builder) {
User user = new User();
user.state = "LOGIN";
user.extension = extension;
//      RestTemplate restTemplate = new RestTemplate();
//      restTemplate.set
RestTemplate restTemplate = builder.basicAuthorization(userId, password).build();
restTemplate.put("https://server/api/User/"+userId, user);

但得到了例外

2018-09-14 22:19:44.038 ERROR 143068 --- [nio-8443-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.client.RestTemplateBuilder]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Customizers must not be null] with root cause
java.lang.IllegalArgumentException: Customizers must not be null
at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.boot.web.client.RestTemplateBuilder.<init>(RestTemplateBuilder.java:104) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_152]

我尝试了以下方法

public String login(@RequestParam(name="userId", required=true) String userId,
@RequestParam(name="password", required=true) String password,
@RequestParam(name="extension", required=true) String extension,
HttpSession session
/*RestTemplateBuilder builder*/) throws KeyManagementException, NoSuchAlgorithmException {
User user = new User();
user.state = "LOGIN";
user.extension = extension;
// turn off SSL checking // https://stackoverflow.com/a/24491820/148844
X509TrustManager[] tm = new X509TrustManager[] {new TrustAllX509TrustManager()}; // from IdS client SDK
SSLContext sc = SSLContext.getInstance("SSL");
sc.init( null, tm, null );
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// set authentication headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
String plainClientCredentials = userId + ":" + password;
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
headers.add("Authorization", "Basic " + base64ClientCredentials);
HttpEntity request = new HttpEntity(null, headers);
// make request
RestTemplate restTemplate = new RestTemplate();
String url = "https://server/api/User/"+userId;
restTemplate.put(url, request, user);

但是得到了错误

org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:766) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:724) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.web.client.RestTemplate.put(RestTemplate.java:495) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]

它适用于curl.


我添加了

restTemplate.setErrorHandler(new ResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse arg0) throws IOException {
byte[] b = new byte[arg0.getBody().available()];
arg0.getBody().read(b);
System.out.println(new String(b));
}
@Override
public boolean hasError(ClientHttpResponse arg0) throws IOException {
return arg0.getRawStatusCode() != 202;
}
});
System.out.println("nnn********************************************************************");
restTemplate.put(url, request, user);

并得到了

********************************************************************
<ApiErrors>
<ApiError>
<ErrorType>Invalid Input</ErrorType>
<ErrorData>User</ErrorData>
<ErrorMessage> : Premature end of file.</ErrorMessage>
</ApiError>
</ApiErrors>

你试过这个吗?

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("username", "password"));

最新更新