这个问题更多地涉及使用Apache Camel发送
multipart/form-data
。我之前曾经尝试过,并通过自定义处理器将头部转换为
multipart/form-data
格式,使用
Content-Disposition: form-data
。
这是我的处理器,将头部转换为
multipart/form-data
格式:
public class PrepareMultipartFormData implements Processor {
private String[] multipartHeaders;
public PrepareMultipartFormData(String... multipartHeaders) {
this.multipartHeaders = multipartHeaders;
}
@Override
public void process(Exchange exchange) throws Exception {
addMultipart(exchange.getIn(), multipartHeaders);
}
private static void addMultipart(Message message, String... multipartKeys){
final String boundary = "---------------------------"+RandomStringUtils.randomAlphanumeric(9);
message.setHeader(Exchange.CONTENT_TYPE, "multipart/form-data;boundary="+boundary);
StringBuilder sb = new StringBuilder("--").append(boundary);
for (String key: multipartKeys) {
sb.append("\r\n")
.append("Content-Disposition: form-data; name=\"").append(key).append("\"")
.append("\r\n\r\n")
.append(message.getHeader(key, String.class))
.append("\r\n")
.append("--").append(boundary);
}
message.setBody(sb.toString());
}
}
请求OAuth令牌需要发送以下内容:
- HTTP头部
- Authorization header - 这是由端点选项
authUsername
和authPassword
指定的标准HTTP组件的一部分
- Content-Type - 这是在我的
PrepareMultipartFormData
处理器中添加的
- 表单数据 - 这些数据是从
PrepareMultipartFormData
处理器中的头部转换而来
- grant_type
- username
- password
- client_id
最终路线可以这样实现:
(将常量替换为某些表达式,以动态设置。如果您只需要响应中的token
,则添加一些解组代码,因为此路线返回JSON)
from("direct:getTokenResponse")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.HTTP_PATH, constant("oauth/token"))
.setHeader("grant_type", constant("password"))
.setHeader("username", constant("admin"))
.setHeader("password", constant("admin1234"))
.setHeader("client_id", constant("spring-security-oauth2-read-write-client"))
.process(new PrepareMultipartFormData("grant_type", "username", "password", "client_id"))
.to("http://localhost:8080?authMethod=Basic&authUsername=oauth-endpoint-username&authPassword=oauth-endpoint-password")
.convertBodyTo(String.class)
.to("log:response");
更新答案,提供更简洁的PrepareMultipartFormData#addMultipart
实现方法,使用MultipartEntityBuilder。
private static void addMultipart(Message message, String... multipartKeys) throws Exception{
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (String key: multipartKeys) {
builder.addTextBody(key, message.getHeader(key, String.class));
}
HttpEntity resultEntity = builder.build();
message.setHeader(Exchange.CONTENT_TYPE, resultEntity.getContentType().getValue());
message.setBody(resultEntity.getContent());
}