【发布时间】:2022-01-26 04:56:46
【问题描述】:
我正在尝试从用 Java 编写的 Google Cloud Function 返回 JSON 格式的数据。我有一个来自 GoogleCloudPlatform/java-doc-samples (https://github.com/GoogleCloudPlatform/java-docs-samples/blob/main/functions/http/http-method/src/main/java/functions/HttpMethod.java) 的示例,它向我展示了如何处理不同类型的 HTTP 方法,但它没有展示如何在响应中编写 JSON。
我想做的事情如下:
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import static java.util.Map.entry;
public class ReturnJSON implements HttpFunction {
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
Map<String, String> returnJSON = Map.ofEntries(
entry("name", "Test User"),
entry("email", "test_user@example.com"),
entry("emotion", "happy")
);
var writer = new PrintWriter(response.getWriter());
writer.write(returnJSON);
}
这样做的最终目标是向 ReturnJSON 函数(部署为某个 URL 的云函数)发送 HTTP 请求,当我使用 JavaScript 获取它时返回 JSON: p>
fetch("https://example.com/return-json", { method: "GET" })
.then(response => response.json())
.then(data => console.log(data));
【问题讨论】:
标签: java json google-cloud-functions httpresponse