本文介绍如何使用不同语言SDK提供的接口,执行HTTP触发器函数。

背景信息

函数计算根据请求头部的Authorization字段校验每一个请求是否合法。只有使用与函数计算一致的签名算法才能通过验证,未包含签名字段或者签名错误的请求,函数计算将返回HTTP 403错误。关于签名算法的更多信息,请参见签名认证

函数计算的SDK已经提供接口执行HTTP函数,且SDK已经实现签名算法,支持对该接口进行签名,无需您手动计算签名。更多信息,请参见SDK列表

说明 如果HTTP触发器设置了允许匿名访问函数,即触发器配置中参数是否需要认证选择为,则无需校验,也无需计算签名。

使用场景

函数计算的Golang,Python和Java语言支持HTTP触发器的签名调用。您可以在以下三种场景,使用函数计算的SDK。
  • 签名场景下调用HTTP触发器。推荐在测试场景中使用。
  • 匿名场景下调用HTTP触发器。推荐在测试场景中使用。
  • 集成场景下对HTTP Request进行签名,然后使用自定义HTTP Client处理签名后的请求,以达到最优的性能以及最佳的扩展性。推荐在生产环境中使用。

使用示例

Golang

更多信息,请参见Golang

安装

使用go mod工具安装。
# install alibabacloud_fc_open20210406
go get -u github.com/alibabacloud-go/fc-open-20210406

使用

  • 签名场景
    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httputil"
        "os"
    
        openapi "github.com/alibabacloud-go/darabonba-openapi/client"
        client "github.com/alibabacloud-go/fc-open-20210406/client"
    
    )
    
    func main() {
        config := &openapi.Config{}
        ak := os.Getenv("ak")
        sk := os.Getenv("sk")
        url := os.Getenv("url")
    
        config.SetAccessKeyId(ak)
        config.SetAccessKeySecret(sk)
        config.SetRegionId("cn-hangzhou")
        c, err := client.NewClient(config)
        if err != nil {
            panic(err)
        }
        method := "POST"
        headers := &http.Header{}
        headers.Add("k1", "v1")
        resp, err := c.InvokeHTTPTrigger(&url, &method, []byte("abc"), headers)
        if err != nil {
            panic(err)
        }
        str, _ := httputil.DumpResponse(resp, true)
        fmt.Printf("response: %+v\n", string(str))
    }
  • 匿名场景
    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httputil"
        "os"
    
        openapi "github.com/alibabacloud-go/darabonba-openapi/client"
        client "github.com/alibabacloud-go/fc-open-20210406/client"
    )
    
    func main() {
        config := &openapi.Config{}
        ak := "dummy-ak"
        sk := "dummy-sk"
        url := os.Getenv("url")
    
        config.SetAccessKeyId(ak)
        config.SetAccessKeySecret(sk)
        config.SetRegionId("cn-hangzhou")
        c, err := client.NewClient(config)
        if err != nil {
            panic(err)
        }
        method := "POST"
        headers := &http.Header{}
        headers.Add("k1", "v1")
        resp, err := c.InvokeAnonymousHTTPTrigger(&url, &method, []byte("abc"), headers)
        if err != nil {
            panic(err)
        }
        str, _ := httputil.DumpResponse(resp, true)
        fmt.Printf("response: %+v\n", string(str))
    }
  • 集成场景
    package main
    
    import (
        "fmt"
        "net/http"
        "net/http/httputil"
        "os"
    
        client "github.com/alibabacloud-go/fc-open-20210406/client"
        openapi "github.com/alibabacloud-go/darabonba-openapi/client"
    )
    
    func main() {
        config := &openapi.Config{}
        ak := os.Getenv("ak")
        sk := os.Getenv("sk")
        url := os.Getenv("url")
    
        config.SetAccessKeyId(ak)
        config.SetAccessKeySecret(sk)
        config.SetRegionId("cn-hangzhou")
        c, err := client.NewClient(config)
        if err != nil {
            panic(err)
        }
        method := "GET"
        request, err := http.NewRequest(method, url, nil)
        if err != nil {
            panic(err)
        }
        request, err = c.SignRequest(request)
        if err != nil {
            panic(err)
        }
        resp, err := http.DefaultClient.Do(request)
        if err != nil {
            panic(err)
        }
        str, _ := httputil.DumpResponse(resp, true)
        fmt.Printf("response: %+v\n", string(str))
    }

Python

更多信息,请参见Python

安装

使用pip工具安装。
# install alibabacloud_fc_open20210406
pip install -U alibabacloud_fc_open20210406

使用

  • 签名场景
    # -*- coding: utf-8 -*-
    import os
    
    from alibabacloud_fc_open20210406.client import Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    ak = os.getenv('ak')
    sk = os.getenv('sk')
    url = os.getenv('url')
    
    client = Client(config=open_api_models.Config(access_key_id=ak,
                                                  access_key_secret=sk,
                                                  region_id='cn-hangzhou'))
    
    resp = client.invoke_httptrigger(url=url,
                                     method="GET",
                                     body="anything".encode(encoding='utf-8'),
                                     headers={"k1": "v1", "k2": "v2"})
  • 匿名场景
    import os
    
    from alibabacloud_fc_open20210406.client import Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    ak = os.getenv('ak')
    sk = os.getenv('sk')
    url = os.getenv('url')
    
    client = Client(config=open_api_models.Config(access_key_id=ak,
                                                  access_key_secret=sk,
                                                  region_id='cn-hangzhou'))
    
    resp = client.invoke_anonymous_httptrigger(url=url,
                                     method="GET",
                                     body="anything".encode(encoding='utf-8'),
                                     headers={"k1": "v1", "k2": "v2"})
  • 集成场景
    import requests
    import os
    
    from alibabacloud_fc_open20210406.client import Client
    from alibabacloud_tea_openapi import models as open_api_models
    
    ak = os.getenv('ak')
    sk = os.getenv('sk')
    url = os.getenv('url')
    
    client = Client(config=open_api_models.Config(access_key_id=ak,
                                                  access_key_secret=sk,
                                                  region_id='cn-hangzhou'))
    
    # build your own request
    req = requests.Request(
        url=url,
        method='GET'
    )
    req = client.sign_request(req)
    with requests.Session() as s:
        prep=s.prepare_request(req)
        resp = s.send(prep)

Java

更多信息,请参见Java

安装

使用Maven工具或Gradle工具管理依赖,Maven依赖坐标如下。
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>fc_open20210406</artifactId>
  <!-- use the latest version instead -->
  <version>1.1.6</version>
</dependency>

使用

  • 签名场景
    package com.aliyun.example;
    
    import com.aliyun.fc_open20210406.Client;
    import com.aliyun.teaopenapi.models.Config;
    import okhttp3.Headers;
    import okhttp3.Response;
    
    import java.nio.charset.StandardCharsets;
    
    
    public class Main {
        public static void main(String[] args) throws Exception {
            String ak = System.getenv("ak");
            String sk = System.getenv("sk");
            String url = System.getenv("url");
            Config config = new Config().setAccessKeyId(ak).setAccessKeySecret(sk).setRegionId("cn-hangzhou");
    
            Client client = new Client(config);
            try (Response res = client.InvokeHTTPTrigger(url, "POST", "mybodystring".getBytes(StandardCharsets.UTF_8), new Headers.Builder().build())) {
                System.out.println(res.toString());
                System.out.println(res.body().string());
            }
        }
    }
  • 匿名场景
    package com.aliyun.example;
    
    import com.aliyun.fc_open20210406.Client;
    import com.aliyun.teaopenapi.models.Config;
    import okhttp3.Headers;
    import okhttp3.Response;
    
    import java.nio.charset.StandardCharsets;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            String ak = System.getenv("ak");
            String sk = System.getenv("sk");
            String url = System.getenv("url");
            Config config = new Config().setAccessKeyId(ak).setAccessKeySecret(sk).setRegionId("cn-hangzhou");
    
            Client client = new Client(config);
            try (Response res = client.InvokeAnonymousHTTPTrigger(url, "POST", "mybodystring".getBytes(StandardCharsets.UTF_8), new Headers.Builder().build())) {
                System.out.println(res.toString());
                System.out.println(res.body().string());
            }
        }
    }
  • 集成场景
    package com.aliyun.example;
    
    import com.aliyun.fc_open20210406.Client;
    import com.aliyun.tea.okhttp.OkHttpClientBuilder;
    import com.aliyun.teaopenapi.models.Config;
    import okhttp3.*;
    
    import java.nio.charset.StandardCharsets;
    
    
    public class Main {
        public static void main(String[] args) throws Exception {
            String ak = System.getenv("ak");
            String sk = System.getenv("sk");
            String url = System.getenv("url");
            Config config = new Config().setAccessKeyId(ak).setAccessKeySecret(sk).setRegionId("cn-hangzhou");
    
            Client client = new Client(config);
            OkHttpClient okHttpClient = new OkHttpClientBuilder().buildOkHttpClient();
    
            Request request = new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(MediaType.parse("application/json"),
                            "mybodystring".getBytes(StandardCharsets.UTF_8)))
                    .build();
    
            // sign your request
            request = client.SignRequest(request);
            try (Response res = okHttpClient.newCall(request).execute()) {
                System.out.println(res.toString());
                System.out.println(res.body().string());
            }
        }
    }