您可以使用HTTP Handler更方便地处理HTTP请求。当调用函数时,函数计算运行您提供的执行方法来处理HTTP请求。本文介绍Java HTTP Handler的结构和特点。
HTTP Handler签名
函数计算提供基于Servlet协议的HTTP入口,形式如下所示。
public interface HttpRequestHandler {
    /**
     * The entrance function of fc http trigger 
     * @param request The servlet request
     * @param response The servlet response
     * @param context The fc context
     * @throws IOException If IO exception happened
     * @throws ServletException If servlet exception happened
     */
    public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) throws IOException, ServletException;
}      HTTP请求处理程序要求您必须为函数配置HTTP触发器,使用HTTP触发器需要将fc-java-core库版本升级到1.3.0及以上版本,示例如下。关于HTTP触发器的详细信息,请参见HTTP触发器概述。
<dependency>
  <groupId>com.aliyun.fc.runtime</groupId>
  <artifactId>fc-java-core</artifactId>
  <version>1.4.1</version>
</dependency>简单示例
package com.aliyun.fc.example;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.HttpRequestHandler;
public class Hello implements HttpRequestHandler {
    public void handleRequest(HttpServletRequest request, HttpServletResponse response, Context context)
            throws IOException, ServletException {
        String requestPath = (String) request.getAttribute("FC_REQUEST_PATH");
        String requestURI = (String) request.getAttribute("FC_REQUEST_URI");
        String requestClientIP = (String) request.getAttribute("FC_REQUEST_CLIENT_IP"); 
        response.setStatus(200);
        response.setHeader("header1", "value1");
        response.setHeader("header2", "value2");
        String body = String.format("Path: %s\n Uri: %s\n IP: %s\n", requestPath, requestURI, requestClientIP);
        OutputStream out = response.getOutputStream();
        out.write((body).getBytes());
    }
}          - HttpServletRequest函数计算的HTTP触发器的接口使用标准的Servlet协议。您的请求会封装成HttpServletRequest对象,请求参数、请求头等均可通过此对象获取。除此之外,函数计算在HttpServletRequest中预封装了一些属性,您可以通过getAttribute方法来获取,具体包括以下内容: - FC_REQUEST_PATH:获取请求的路径。 
- FC_REQUEST_URI:获取请求的URI。 
- FC_REQUEST_CLIENT_IP:获取请求的Client IP地址。 
 
- HttpServletResponse您可以通过标准的HttpServletResponse协议对象来返回响应头和响应体。 
- contextcontext参数中包含一些函数的运行时信息(例如Request ID、临时AccessKey等),其类型是 com.aliyun.fc.runtime.Context。
示例程序
函数计算官方库包含了使用各种处理程序类型和接口的示例应用程序。每个示例应用程序都包含用于轻松编译部署的方法。例如:
- java11-blank-http:HTTP回调处理程序。
该文章对您有帮助吗?