新增远程调用form表单

This commit is contained in:
wanggeng 2021-09-21 20:11:33 +08:00
parent 5b9b3e2372
commit f1ef15cba0
2 changed files with 77 additions and 35 deletions

View File

@ -12,6 +12,8 @@ import ink.wgink.util.RegexUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.UnsupportedEncodingException;
@ -34,7 +36,6 @@ import java.util.regex.Pattern;
* @Version: 1.0
*/
public class RestRemoteHandler implements InvocationHandler {
private static final Logger LOG = LoggerFactory.getLogger(RestRemoteHandler.class);
private static final Pattern PATH_VARIABLE = Pattern.compile("\\{[^\\s\\}]+\\}");
@Override
@ -58,6 +59,7 @@ public class RestRemoteHandler implements InvocationHandler {
Map<String, String> pathVariableParams = getPathVariableParams(method.getParameters(), args);
Map<String, String> queryVariableParams = getQueryVariableParams(method.getParameters(), args);
Map<String, String> headerVariableParams = getHeaderVariableParams(method.getParameters(), args);
MultiValueMap<String, Object> formVariableParams = null;
String uri;
Object requestBody = null;
RequestMethod requestMethod;
@ -76,15 +78,16 @@ public class RestRemoteHandler implements InvocationHandler {
requestMethod = RequestMethod.POST;
RemotePostMethod postMethod = method.getAnnotation(RemotePostMethod.class);
uri = postMethod.value();
formVariableParams = getFormVariableParams(method.getParameters(), args);
if (formVariableParams == null) {
requestBody = getRequestBody(method.getParameters(), args);
checkJsonBody(requestBody);
}
} else if (method.isAnnotationPresent(RemotePutMethod.class)) {
// PUT请求
requestMethod = RequestMethod.PUT;
RemotePutMethod putMethod = method.getAnnotation(RemotePutMethod.class);
uri = putMethod.value();
requestBody = getRequestBody(method.getParameters(), args);
checkJsonBody(requestBody);
} else {
return null;
}
@ -93,19 +96,8 @@ public class RestRemoteHandler implements InvocationHandler {
checkPathVariableParams(pathVariable, pathVariableParams);
uri = buildUri(uri, pathVariable, pathVariableParams);
String remoteFullPath = buildFullUri(remotePath, uri, queryVariableParams);
// LOG.debug("remoteFullUri: {}", remoteFullUri);
// LOG.debug("requestBody: {}", requestBody);
// LOG.debug("headerVariableParams: {}", headerVariableParams);
// LOG.debug("requestMethod: {}", requestMethod.name());
System.out.println("remoteFullUri: " + remoteFullPath);
System.out.println("requestBody: " + requestBody);
System.out.println("headerVariableParams: " + headerVariableParams);
System.out.println("requestMethod: " + requestMethod.name());
RestRemoteRequest restRemoteRequest = new RestRemoteRequest();
return restRemoteRequest.request(requestMethod, remoteFullPath, headerVariableParams, requestBody, method.getGenericReturnType());
return restRemoteRequest.request(requestMethod, remoteFullPath, headerVariableParams, formVariableParams, requestBody, method.getGenericReturnType());
}
/**
@ -179,6 +171,34 @@ public class RestRemoteHandler implements InvocationHandler {
return queryVariableParamsMap;
}
/**
* 表单参数
*
* @param parameters
* @param args
* @return
*/
private MultiValueMap<String, Object> getFormVariableParams(Parameter[] parameters, Object[] args) throws UnsupportedEncodingException {
MultiValueMap<String, Object> formVariableParamsMap = new LinkedMultiValueMap<>();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if (!parameter.isAnnotationPresent(RemoteFormParams.class)) {
continue;
}
RemoteFormParams annotation = parameter.getAnnotation(RemoteFormParams.class);
String variableName = annotation.value();
if (StringUtils.isBlank(variableName)) {
throw new ParamsException("表单参数 " + parameter.getName() + " 名称不能为空");
}
Object arg = args[i];
if (arg == null) {
continue;
}
formVariableParamsMap.add(variableName, URLEncoder.encode(arg.toString(), "UTF-8"));
}
return formVariableParamsMap;
}
/**
* 请求头
*
@ -288,17 +308,6 @@ public class RestRemoteHandler implements InvocationHandler {
}
}
/**
* 校验请求主体
*
* @param requestBody
*/
private void checkJsonBody(Object requestBody) {
if (requestBody == null) {
throw new ParamsException("请求主体不能为空");
}
}
/**
* 校验远程请求路径
*

View File

@ -7,6 +7,7 @@ import ink.wgink.exceptions.rpc.RemoteRequestException;
import ink.wgink.exceptions.rpc.RemoteResponseException;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
@ -36,14 +37,19 @@ public class RestRemoteRequest {
this.restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
}
public Object request(RequestMethod requestMethod, String remoteUri, Map<String, String> headers, Object jsonBody, Type resultType) {
public Object request(RequestMethod requestMethod, String remoteUri, Map<String, String> headers, MultiValueMap<String, Object> formVariableParams, Object jsonBody, Type resultType) {
String result;
if (RequestMethod.GET.equals(requestMethod)) {
result = get(remoteUri, headers);
} else if (RequestMethod.DELETE.equals(requestMethod)) {
result = delete(remoteUri, headers);
} else if (RequestMethod.POST.equals(requestMethod)) {
// form表单优先
if (formVariableParams != null) {
result = post(remoteUri, headers, formVariableParams);
} else {
result = post(remoteUri, headers, jsonBody);
}
} else if (RequestMethod.PUT.equals(requestMethod)) {
result = put(remoteUri, headers, jsonBody);
} else {
@ -62,7 +68,7 @@ public class RestRemoteRequest {
*/
public String get(String remoteUri, Map<String, String> headers) {
try {
HttpEntity<String> httpEntity = getHttpEntity(headers, null);
HttpEntity<String> httpEntity = getHttpEntity(headers, null, null);
ResponseEntity<String> responseEntity = restTemplate.exchange(remoteUri, HttpMethod.GET, httpEntity, String.class);
return getStringResponse(responseEntity);
} catch (Exception e) {
@ -84,7 +90,7 @@ public class RestRemoteRequest {
*/
public String delete(String remoteUri, Map<String, String> headers) {
try {
HttpEntity<String> httpEntity = getHttpEntity(headers, null);
HttpEntity<String> httpEntity = getHttpEntity(headers, null, null);
ResponseEntity<String> responseEntity = restTemplate.exchange(remoteUri, HttpMethod.DELETE, httpEntity, String.class);
return getStringResponse(responseEntity);
} catch (Exception e) {
@ -105,7 +111,28 @@ public class RestRemoteRequest {
*/
public String post(String remoteUri, Map<String, String> headers, Object jsonBody) {
try {
HttpEntity<String> httpEntity = getHttpEntity(headers, jsonBody);
HttpEntity<String> httpEntity = getHttpEntity(headers, null, jsonBody);
ResponseEntity<String> responseEntity = restTemplate.exchange(remoteUri, HttpMethod.POST, httpEntity, String.class);
return getStringResponse(responseEntity);
} catch (Exception e) {
if (e instanceof HttpClientErrorException) {
HttpClientErrorException exception = (HttpClientErrorException) e;
throw new RemoteResponseException(exception.getResponseBodyAsString());
}
throw new RemoteRequestException(e.getMessage(), e);
}
}
/**
* POST请求
*
* @param remoteUri
* @param headers
* @return
*/
public String post(String remoteUri, Map<String, String> headers, MultiValueMap<String, Object> formVariableParams) {
try {
HttpEntity<String> httpEntity = getHttpEntity(headers, formVariableParams, null);
ResponseEntity<String> responseEntity = restTemplate.exchange(remoteUri, HttpMethod.POST, httpEntity, String.class);
return getStringResponse(responseEntity);
} catch (Exception e) {
@ -126,7 +153,7 @@ public class RestRemoteRequest {
*/
public String put(String remoteUri, Map<String, String> headers, Object jsonBody) {
try {
HttpEntity<String> httpEntity = getHttpEntity(headers, jsonBody);
HttpEntity<String> httpEntity = getHttpEntity(headers, null, jsonBody);
ResponseEntity<String> responseEntity = restTemplate.exchange(remoteUri, HttpMethod.PUT, httpEntity, String.class);
return getStringResponse(responseEntity);
} catch (Exception e) {
@ -145,14 +172,20 @@ public class RestRemoteRequest {
* @param jsonBody
* @return
*/
private HttpEntity<String> getHttpEntity(Map<String, String> headerMap, Object jsonBody) {
private HttpEntity<String> getHttpEntity(Map<String, String> headerMap, MultiValueMap<String, Object> formVariableParams, Object jsonBody) {
HttpEntity<String> httpEntity;
if (jsonBody != null) {
HttpHeaders httpHeaders = getHttpHeaders(headerMap);
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
if (jsonBody instanceof Collection) {
httpEntity = new HttpEntity(JSONArray.toJSONString(jsonBody), getHttpHeaders(headerMap));
} else {
httpEntity = new HttpEntity(JSONObject.toJSONString(jsonBody), getHttpHeaders(headerMap));
}
} else if (formVariableParams != null) {
HttpHeaders httpHeaders = getHttpHeaders(headerMap);
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
httpEntity = new HttpEntity(formVariableParams, httpHeaders);
} else {
httpEntity = new HttpEntity(getHttpHeaders(headerMap));
}
@ -167,8 +200,8 @@ public class RestRemoteRequest {
*/
private HttpHeaders getHttpHeaders(Map<String, String> headersMap) {
HttpHeaders httpHeaders = new HttpHeaders();
// 接收JSON格式返回
httpHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE);
httpHeaders.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
for (Map.Entry<String, String> kv : headersMap.entrySet()) {
httpHeaders.add(kv.getKey(), kv.getValue());
}