先看这个答案,再看我的答案:<a href="https://stackoverflow.com/questions/36917469/how-can-i-work-around-youtube-api-embed-restrictions-like-other -websites?answertab=active#tab-top">如何像其他网站一样解决 YouTube API 嵌入限制?
if ("sun/net/www/protocol/http/HttpURLConnection".equals(className)) {
try {
CtClass ctClass = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
CtMethod method = ctClass.getDeclaredMethod("getFilteredHeaderFields");
// inject cross domain code
injectCrossDomain(method);
byteCode = ctClass.toBytecode();
ctClass.detach();
} catch (Exception e) {
e.printStackTrace();
throw new CatalinaException(e);
}
}
----------------injectCrossDomain----------------
private void injectCrossDomain(CtMethod method) throws CannotCompileException {
StringBuilder sb = new StringBuilder();
sb.append("if (this.filteredHeaders != null) {");
sb.append(" return this.filteredHeaders;");
sb.append("} else {");
sb.append(" java.util.HashMap var2 = new java.util.HashMap();");
sb.append(" java.util.Map var1;");
sb.append(" if (this.cachedHeaders != null) {");
sb.append(" var1 = this.cachedHeaders.getHeaders();");
sb.append(" } else {");
sb.append(" var1 = this.responses.getHeaders();");
sb.append(" }");
sb.append(" java.util.Iterator var3 = var1.entrySet().iterator();");
sb.append(" while(var3.hasNext()) {");
sb.append(" java.util.Map.Entry var4 = (java.util.Map.Entry)var3.next();");
sb.append(" String var5 = (String)var4.getKey();");
sb.append(" java.util.List var6 = (java.util.List)var4.getValue();");
sb.append(" java.util.ArrayList var7 = new java.util.ArrayList();");
sb.append(" java.util.Iterator var8 = var6.iterator();");
sb.append(" while(var8.hasNext()) {");
sb.append(" String var9 = (String)var8.next();");
sb.append(" String var10 = this.filterHeaderField(var5, var9);");
sb.append(" if (var10 != null) {");
sb.append(" var7.add(var10);");
sb.append(" }");
sb.append(" }");
sb.append(" if (!var7.isEmpty()) {");
// insert Access-Control-Allow-Origin:*
sb.append(" var2.put(\"Access-Control-Allow-Origin\", java.util.Collections.singletonList(\"*\"));");
// insert Access-Control-Allow-Headers:*
sb.append(" var2.put(\"Access-Control-Allow-Headers\", java.util.Collections.singletonList(\"*\"));");
sb.append(" var2.put(var5, java.util.Collections.unmodifiableList(var7));");
sb.append(" }");
sb.append(" }");
sb.append(" return this.filteredHeaders = java.util.Collections.unmodifiableMap(var2);");
sb.append("}");
method.setBody(sb.toString());
}