|
27 | 27 | import java.util.ArrayList; |
28 | 28 | import java.util.Arrays; |
29 | 29 | import java.util.Enumeration; |
| 30 | +import java.util.HashMap; |
30 | 31 | import java.util.List; |
| 32 | +import java.util.Map; |
| 33 | +import java.util.Map.Entry; |
31 | 34 | import java.util.Random; |
| 35 | +import java.util.Set; |
32 | 36 | import java.util.concurrent.TimeoutException; |
33 | 37 |
|
34 | 38 | import javax.servlet.http.HttpServletRequest; |
@@ -1025,16 +1029,40 @@ public String delegate( |
1025 | 1029 | headers.put(COOKIE, c); |
1026 | 1030 | } |
1027 | 1031 | } |
1028 | | - try { |
1029 | | - request.getParameterMap().remove("$_delegate_url"); |
1030 | | - } catch (Exception e) { |
1031 | | - // TODO: handle exception |
| 1032 | + |
| 1033 | + //可能是 HTTP POST FORM,即便是 HTTP POST JSON,URL 的参数也要拼接,尽可能保持原样 if (method == HttpMethod.GET) { |
| 1034 | + Map<String, String[]> map = request.getParameterMap(); |
| 1035 | + |
| 1036 | + if (map != null) { |
| 1037 | + map = new HashMap<>(map); //解决 throw exception: Unmodified Map |
| 1038 | + map.remove("$_except_headers"); |
| 1039 | + map.remove("$_delegate_url"); |
| 1040 | + |
| 1041 | + Set<Entry<String, String[]>> set = map == null ? null : map.entrySet(); |
| 1042 | + |
| 1043 | + if (set != null && set.isEmpty() == false) { |
| 1044 | + |
| 1045 | + if (url.contains("?") == false) { |
| 1046 | + url += "?"; |
| 1047 | + } |
| 1048 | + boolean first = url.endsWith("?"); |
| 1049 | + |
| 1050 | + for (Entry<String, String[]> e : set) { |
| 1051 | + if (e != null) { |
| 1052 | + url += ((first ? "" : "&") + e.getKey() + "=" + ( e.getValue() == null || e.getValue().length <= 0 ? "" : StringUtil.getString(e.getValue()[0]) )); |
| 1053 | + first = false; |
| 1054 | + } |
| 1055 | + } |
| 1056 | + } |
1032 | 1057 | } |
| 1058 | + // } |
1033 | 1059 |
|
1034 | 1060 | RestTemplate client = new RestTemplate(); |
1035 | | - // 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交 |
1036 | | - HttpEntity<String> requestEntity = new HttpEntity<>(method == HttpMethod.GET ? JSON.toJSONString(request.getParameterMap()) : body, headers); |
1037 | | - // 执行HTTP请求 |
| 1061 | + // 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交 |
| 1062 | + HttpEntity<String> requestEntity = new HttpEntity<>(method == HttpMethod.GET ? null : body, headers); |
| 1063 | + // 执行HTTP请求,这里可能抛异常,不要包装,直接让它抛,能够在浏览器 Console/XHR/{i}/Preview |
| 1064 | + // 看到 error: "Internal Server Error" message: "405 null" 之类的包括信息, |
| 1065 | + // 包装后反而容易混淆,并且会因为 JSON 结构不一致导致解析问题 |
1038 | 1066 | ResponseEntity<String> entity = client.exchange(url, method, requestEntity, String.class); |
1039 | 1067 |
|
1040 | 1068 | HttpHeaders hs = entity.getHeaders(); |
|
0 commit comments