Servlet 未访问 Google 应用引擎(Google App Engine,简称 GAE)API 的原因可能有以下几点:
要解决这个问题,请按照以下步骤操作:
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class MyServlet extends HttpServlet {
private Storage storage;
@Override
public void init() throws ServletException {
try {
// 使用服务帐户密钥文件创建凭据
GoogleCredentials credentials = GoogleCredentials.fromStream(
MyServlet.class.getResourceAsStream("/path/to/your/keyfile.json"));
// 创建 Google Cloud Storage 客户端
storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
} catch (IOException e) {
throw new ServletException("Failed to initialize Google Cloud Storage client", e);
}
}
// 其他方法...
}
在 Servlet 中,你可以使用创建的客户端对象来访问 Google Cloud API。例如,使用 Google Cloud Storage 客户端上传文件:
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
public void uploadFile(String bucketName, String objectName, InputStream inputStream, long size) throws IOException {
Bucket bucket = storage.get(bucketName);
Blob blob = bucket.create(objectName, inputStream, size);
// 处理上传的文件...
}
领取专属 10元无门槛券
手把手带您无忧上云