You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.3 KiB
68 lines
2.3 KiB
package com.dsideal.gw.Controller;
|
|
|
|
import com.jfinal.core.Controller;
|
|
import com.jfinal.kit.PropKit;
|
|
import okhttp3.MediaType;
|
|
import okhttp3.OkHttpClient;
|
|
import okhttp3.Request;
|
|
import okhttp3.RequestBody;
|
|
import okhttp3.Response;
|
|
|
|
import java.io.IOException;
|
|
|
|
public class ApiController extends Controller {
|
|
|
|
private OkHttpClient client = new OkHttpClient();
|
|
|
|
public void index() {
|
|
String path = getPara(); // 获取请求路径
|
|
System.out.println(path);
|
|
String serviceUrl = route(path); // 根据路径决定转发到哪个微服务
|
|
|
|
if (serviceUrl == null) {
|
|
renderJson("error", "服务未找到");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
String method = getRequest().getMethod();
|
|
Request.Builder requestBuilder = new Request.Builder()
|
|
.url(serviceUrl)
|
|
.header("Authorization", getHeader("Authorization"));
|
|
|
|
if ("POST".equalsIgnoreCase(method)) {
|
|
String jsonPayload = getRawData(); // 获取请求体中的JSON数据
|
|
MediaType JSON = MediaType.get("application/json; charset=utf-8");
|
|
RequestBody body = RequestBody.create(JSON, jsonPayload);
|
|
requestBuilder.post(body);
|
|
}
|
|
|
|
Request request = requestBuilder.build();
|
|
Response response = client.newCall(request).execute();
|
|
|
|
if (response.isSuccessful()) {
|
|
renderJson(response.body().string());
|
|
} else {
|
|
renderJson("error", "服务请求失败");
|
|
}
|
|
} catch (IOException e) {
|
|
renderJson("error", "发生异常: " + e.getMessage());
|
|
}
|
|
}
|
|
|
|
private String route(String path) {
|
|
String[] prefixes = PropKit.getProp().getProperties().stringPropertyNames().stream()
|
|
.filter(key -> key.endsWith(".prefix"))
|
|
.toArray(String[]::new);
|
|
|
|
for (String prefixKey : prefixes) {
|
|
String prefix = PropKit.get(prefixKey);
|
|
if (path.startsWith(prefix)) {
|
|
String serviceKey = prefixKey.replace(".prefix", ".url");
|
|
return PropKit.get(serviceKey) + path;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
} |