AWS apigateway是否会更改http正文?如何阻止它执行此操作? [英] Does AWS apigateway change http body? How can I stop it from doing this?

查看:98
本文介绍了AWS apigateway是否会更改http正文?如何阻止它执行此操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AWS apigateway是否更改http正文?如何阻止它执行此操作?

Does AWS apigateway change http body? How can I stop it from doing this?

我的应用程序:

(1)前端"UI",使用"POST方法"发送"http请求",该"POST请求"通过"form-data"在"body"中包含"zip文件".

(1) A front end "UI" that sends a "http request" using "POST method" that contains a "zip file" in "body" through "form-data".

(2)AWS"apigateway"接收到此请求并将其转发到"Lambda代理"

(2) AWS "apigateway" receives this request and forward it to "Lambda Proxy"

(3)通过python编码实现的AWS"Lambda"收到此请求,并将此zip文件解压缩到一个临时文件夹.

(3) AWS "Lambda" implemented by python coding receives this request and decompresses this zip file to a temporary folder.

我面临的问题:(1)和(2)可以正常工作,但是在(3)中,lambda的pythong程序无法解压缩文件.

The problem I'm facing: (1) and (2) works fine, but in (3) the pythong program at lambda failed to decompress the file.

我的发现:

似乎从"UI"发送时,正文包含zip文件的二进制数据如下所示:

It seems that when sending from the "UI" the body contains the binary data of the zip file like below:

"PK \ x03 \ x04 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \x06 \ x00 \ x00 \ x00x2.txtPK \ x03 \ x04 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \x00 \ x00 \ x06 \ x00 \ x00 \ x00x1.txtPK \ x01 \ x02 \ x14 \ x00 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00x2.txtPK \ x01 \ x02 \ x14 \ x00 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00\ x00 \ x00 \ x00 $ \ x00 \ x00 \ x00x1.txtPK \ x05 \ x06 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x02 \ x00h \ x00 \ x00 \ x00 \ x00H \ x00 \ x00 \ x00 \ x00 \ x00 \x00"

"PK\x03\x04\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00x2.txtPK\x03\x04\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00x1.txtPK\x01\x02\x14\x00\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00x2.txtPK\x01\x02\x14\x00\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00$\x00\x00\x00x1.txtPK\x05\x06\x00\x00\x00\x00\x02\x00\x02\x00h\x00\x00\x00H\x00\x00\x00\x00\x00"

但是在(3)在lambda的python代码中,如果我们只是简单地返回如下所示的响应:

But at (3) the python code at lambda, if we just simply returns the response like below:

response = {
    "statusCode": 200,
    "headers": {
        "lambda-response": str(event["body"])
    },
    "body": "",
    "isBase64Encoded": False
}

返回响应

将发现主体中的二进制数据,好像apigateway已经更改了内容

will find that the binary data in the body, seems like apigateway has changed the content

来自:

"PK \ x03 \ x04 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \x06 \ x00 \ x00 \ x00x2.txtPK \ x03 \ x04 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \x00 \ x00 \ x06 \ x00 \ x00 \ x00x1.txtPK \ x01 \ x02 \ x14 \ x00 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00x2.txtPK \ x01 \ x02 \ x14 \ x00 \ n \ x00 \ x00 \ x00 \ x00 \ x00 \ xd6; TO \ x00 \ x00 \ x00 \ x00 \ x00 \ x00\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00\ x00 \ x00 \ x00 $ \ x00 \ x00 \ x00x1.txtPK \ x05 \ x06 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x02 \ x00h \ x00 \ x00 \ x00 \ x00H \ x00 \ x00 \ x00 \ x00 \ x00 \x00"

"PK\x03\x04\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00x2.txtPK\x03\x04\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00x1.txtPK\x01\x02\x14\x00\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00x2.txtPK\x01\x02\x14\x00\n\x00\x00\x00\x00\x00\xd6;TO\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00$\x00\x00\x00x1.txtPK\x05\x06\x00\x00\x00\x00\x02\x00\x02\x00h\x00\x00\x00H\x00\x00\x00\x00\x00"

进入:

"PK \ u0003 \ u0004 \ n \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ ufffd; TO \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \u0006 \ u0000 \ u0000 \ u0000x2.txtPK \ u0003 \ u0004 \ n \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ ufffd; TO \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \u0000 \ u0000 \ u0006 \ u0000 \ u0000 \ u0000x1.txtPK \ u0001 \ u0002 \ u0014 \ u0000 \ n \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ ufffd; TO \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0006 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000\ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000x2.txtPK \ u0001 \ u0002 \ u0014 \ u0000 \ n \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ ufffd; TO \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000\ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0006 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000\ u0000 \ u0000 \ u0000 $ \ u0000 \ u0000 \ u0000x1.txtPK \ u0005 \ u0006 \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \ u0002 \ u0000 \ u0002 \ u0000h \ u0000 \ u0000 \ u0000H \ u0000 \ u0000 \ u0000 \ u0000 \ u0000 \u0000 \ r \ n"

"PK\u0003\u0004\n\u0000\u0000\u0000\u0000\u0000\ufffd;TO\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0006\u0000\u0000\u0000x2.txtPK\u0003\u0004\n\u0000\u0000\u0000\u0000\u0000\ufffd;TO\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0006\u0000\u0000\u0000x1.txtPK\u0001\u0002\u0014\u0000\n\u0000\u0000\u0000\u0000\u0000\ufffd;TO\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0006\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000\u0000\u0000\u0000\u0000\u0000x2.txtPK\u0001\u0002\u0014\u0000\n\u0000\u0000\u0000\u0000\u0000\ufffd;TO\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0006\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000 \u0000\u0000\u0000$\u0000\u0000\u0000x1.txtPK\u0005\u0006\u0000\u0000\u0000\u0000\u0002\u0000\u0002\u0000h\u0000\u0000\u0000H\u0000\u0000\u0000\u0000\u0000\r\n"

哪个很奇怪,我该怎么做才能阻止这种情况?

Which is weird, what can I do to stop this?

(2019/12/17更新)我正在使用的lambda代码下方.

(2019/12/17 update) below the lambda code I'm using.

import json # to decode json
import os   # file IO
import shutil   # file IO (use this to recursively force remove a directory)

print('Loading function')

def decompress_zip_file(src_file_path, dest_dir_path):
    '''
        Decompress a zip file into a directory.

    Args:
        src_file_path (Srting): source zip file's path.
        dest_dir_path (Srting): the destination of the output directory.
    Returns:
        isSuccess (bool): the operation is successful or not.
    '''
    error_msg = "Nothing."
    try:
        if(os.path.isdir(dest_dir_path)):
            shutil.rmtree(dest_dir_path)

        with zipfile.ZipFile(src_file_path, 'r') as zip_ref:
            zip_ref.extractall(dest_dir_path)
    except Exception as ep:
        error_msg = "Error in decompress_zip_file(), ep={}:{}".format(type(ep).__name__, str(ep))
        print(error_msg)
        return (False, error_msg)

    return (True, error_msg)


def decompress_zip_file_from_content_in_binary(src_file_in_binary, dest_dir_path):
    '''
        Decompress a zip file content into a directory.

    Args:
        src_file_in_binary (byte array): source zip file's content in binary format.
        dest_dir_path (Srting): the destination of the output directory.
    Returns:
        isSuccess (bool): the operation is successful or not.
    '''

    # write the obtained binary data into a tmp zip file
    tmp_file_path = "/tmp/tmp.zip"
    if(os.path.isfile(tmp_file_path)):
        os.remove(tmp_file_path)

    output_file = open(tmp_file_path, 'wb')
    output_file.write(src_file_in_binary)
    output_file.close()

    (isSuccess, error_msg) = decompress_zip_file(tmp_file_path, dest_dir_path)

    return (isSuccess, error_msg)

def convert_from_http_body_encoding_to_local_binary(extracted_file_from_http_body_str):
    '''
        Extract the file (in binary string format) from event['body'] encoding to local binary encoding.

    Args:
        extracted_file_from_http_body_str (string): the event['body'] file (in binary string format),.
    Returns:
        zipfile_binary1 (binary array): the conversion result.
    '''
    zipfile_binary1 = bytes(extracted_file_from_http_body_str, encoding = "ascii") # convert into a zipfile in binary format    

    return zipfile_binary1

def extract_zipfile_binary_from_body(body_str):
    '''
        Extract the zipfile (in binary format) from event['body'] string.

    Args:
        body_str (string): the event['body'] string.
    Returns:
        (binary array): the conversion result.
    '''

    retValue = ""

    tmpArray = body_str.split("application/zip") # split the content based on MIME part field data; cut the head
    if(len(tmpArray) > 1):
        retValue += "entered-Lv1."
        tmpArray = tmpArray[1].split("PK") # split the content based on zip file header.
        if(len(tmpArray) > 1):
            retValue += "entered-Lv2."
            zipfile_str = "PK" + 'PK'.join(tmpArray[1:]) # add back the zip file header            
            tmpArray = zipfile_str.split("------WebKitFormBoundary") # split the content based on MIME part field data; cut the tail
            if(len(tmpArray) > 1):                
                zipfile_str = tmpArray[0]                            
                zipfile_binary = convert_from_http_body_encoding_to_local_binary(zipfile_str)
                retValue = zipfile_binary

    return retValue

def handler(event, context):
    '''Provide an event that contains the following keys:
      - operation: one of the operations in the operations dict below
      - payload: a parameter to pass to the operation being performed
    '''    

    # set the mapping table for "operation" x "return value"
    operations = {        
        'unzip': lambda x: decompress_zip_file_from_content_in_binary(**x), # unzip an uploaded file
        'ping': lambda x: 'pong' # respond to ping req.
    }

    # because we use "Lambda Proxe", means we have api-gateway forward the whole packet without resolving it for lambda.
    event_headers = event["headers"] 
    operation = event_headers['operation']    
    event_body = event["body"] 

    if(operation == 'unzip'):
        src_file_in_binary = extract_zipfile_binary_from_body(event_body)
        payload_json = {}
        payload_json['src_file_in_binary'] = src_file_in_binary
        payload_json['dest_dir_path'] = "/tmp/tmp_zipfile_output"
        event_headers["payload"] = payload_json        

    if operation in operations:
        responseBody = operations[operation](event_headers.get('payload'))

        response = {
            "statusCode": 200,
            "headers": {
                "lambda-response": str(responseBody) # the api-gateway will forward the header to the front end.
            },
            "body": "",
            "isBase64Encoded": False
        }

        return response

    else:
        raise ValueError('Unrecognized operation "{}"'.format(operation))

推荐答案

以下是来自AWS支持的响应.LGTM.请将其保留在此处,以便以后人们可以看到解决此问题的方法.

Below is a response from AWS support. LGTM. Leave it here so that people can see the solution to this issue in the future.

======================下面是来自AWS支持的响应==================

=====================Below is the response from AWS support ==================

感谢您与AWS Premium支持联系.我是Jyoti,今天我将为您提供帮助.

Thank you for contacting AWS Premium Support. I am Jyoti, and I will assist you with this case today.

从案例通信中,我了解到您担心API Gateway会进行修改代理到Lambda函数之前的二进制数据有效载荷.如果我的理解是错误的,请纠正我.

From the case correspondence, I understand that you are concerned that API Gateway modifies the binary data payload before proxying to your Lambda function. Please correct me if my understanding is wrong.

如果存在以下情况,API网关会将二进制数据有效负载修改为UTF-8编码的JSON字符串:API已配置为其默认设置.因此,这是预期的行为.
请注意,根据[1],我们必须将API配置为支持二进制有效负载API网关中的我们的API.API网关无法按原样发送二进制文件,因为它必须发送lambda代理的JSON主体.因此,默认情况下,它将数据/有效载荷编码为UTF-8.

API gateway does modify the binary data payload into UTF-8 encoded JSON strings if the API is configured at its default settings. Hence this is an expected behaviour.
Kindly note, as per [1], we must configure the API to support binary payloads for our API in API Gateway. API Gateway can not send binary as is, since it has to send a JSON body to the lambda proxy. Hence, it encodes the data/payload in UTF-8 by default.

为了克服上述挑战,我们需要添加所需的二进制媒体类型(在这种情况下为application/zip)到binaryMediaTypes列表在RestApi资源的设置页面上.有关如何实现的更多信息这个,请参考这里-> [2].如果未定义此属性,则有效负载如[1]中所述,将其作为UTF-8编码的JSON字符串进行处理.

In order to overcome the aforementioned challenge, we need to add the desired binary media types (application/zip in this case) to the binaryMediaTypes list on the RestApi resource's settings page. For further information on how to achieve this, please refer here --> [2]. If this property is not defined, the payloads are handled as UTF-8 encoded JSON strings as mentioned in [1].

这就是为什么您的请求中的文件使用UTF-8编码的原因.配置API之后,Lambda接收到的事件将是Base64编码的字符串.

This is why the file in your request looks UTF-8 encoded. After configuring the API, the event received by the Lambda would be a Base64-encoded string.

如果您要对此对象(编码的请求正文或'event ["body"]')进行操作,那么您可以按照以下步骤将base64编码的字符串解码为其原始二进制格式下面几行(在python运行时的情况下):

If you want to conduct operations on this object (the encoded request body or 'event["body"]'), then you may decode the base64-encoded string to its orginal binary form by following the below lines (in case of python runtime) :

import base64
coded_string = str(event["body"])
base64.b64decode(coded_string)

故障排除:

我试图在您的环境中复制您的设置.而不是应用程序的前端"UI",我使用Postman作为客户端,其余设置(API网关和Lambda)相似.我从Postman向我的API发出POST请求,请求标头为"Content-Type"和"Accept",两者都设置为值"application/zip",即正在发送的二进制媒体类型,响应中也期望如此.我的API已配置为支持二进制媒体类型在请求正文中传递.我已经在API的binaryMediaTypes列表中添加了"application/zip".最后,在Lambda函数中,我正在解码base64编码的请求正文(即event ["body"])通过使用base64库(在python中)将其恢复为原始二进制格式.

Troubleshooting:

I tried to replicate your setup in my environment. Instead of the frontend 'UI' of the application, I used Postman as a client, while the rest of the setup (API Gateway and Lambda) are similar. I am making a POST request to my API from Postman, with the request headers 'Content-Type' and 'Accept', both set to the value 'application/zip', which is the binary media type that is being sent and also being expected in the response. My API has been configured to support binary media types being passed in the request body. I have added 'application/zip' in the binaryMediaTypes list for the API. Finally, in the Lambda function I am decoding the base64-encoded request body (i.e. event["body"]) to its original binary form by using the base64 library (in python).

如果您仍然想通过返回二进制文件来确认请求的表单数据的一致性数据中,您可以参考以下代码段:

If you still want to confirm the consistency of your request's form-data out by returning the binary data in your response, you can refer to the following snippet:

response {
        'isBase64Encoded': True,                            #Ensure the body is base encoded 
        'statusCode': 200,
        'headers': { "Content-Type": "applicaiton/zip" },   #Define the Content-Type
        'body': event["body"]                               #Response Body returns the Base64-encoded value    
    }

我们将isBase64Encoded参数设置为True,API Gateway会自动解码响应主体取决于Content-Type(即二进制数据/媒体类型)客户端(以我的邮递员为例)设置为接收(即application/zip).请注意,接受"我在标头中发送的标头用于验证响应正文是否包含二进制文件数据类型,提出了要求.

We set the isBase64Encoded parameter to True and API Gateway automatically decodes the response body depending on the Content-Type (i.e. the binary data/media type) that the client (in my case Postman), is set to receive (i.e. application/zip). Kindly note, the 'Accept' header that I had sent in my header, is to validate that the response body contains the binary data type, the request was made for.

以上响应正文与首次发送的请求正文二进制数据相同通过API,在我的设置中.

The above response body was the same as the request body binary data that was first sent through the API, in my setup.

希望我已经解决了您的担忧.但是,如果您仍需要实施方面的帮助,请再次与我们联系,我们将竭诚为您服务.

Hope I have addressed your concerns. However, if you still need help with the implementation, please contact us again and I will be happy to assist you.

References: 
=-=-=-=--=-=-=-=-=-=
[1] Support Binary Payloads in API Gateway: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings.html 
[2] Enable Binary Support Using the API Gateway Console: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-configure-with-console.html 

最诚挚的问候,

Jyoti Prakash P.亚马逊网络服务

Jyoti Prakash P. Amazon Web Services

我意识到我的内容类型实际上是多部分内容,而不是application/zip,因此我再次修改了设置,然后它起作用了.以下是AWS支持人员的帮助.非常感谢他们的帮助.

I realize that my content type is actually multipart instead of application/zip so I modified again the setting then it worked. Below is the help from AWS support. Many thanks to their help.

非常感谢您详细介绍您的应用程序流程和日志.现在,我知道您的HTTP请求标头'content-type'设置为'multipart/form-data'.我同意,对于要上传文件的Web表单,将内容类型设置为表单数据是很常见的,AWS API Gateway确实支持它.您想知道是否可以在不更改前端代码的情况下阻止UTF-8编码.如果我的理解是错误的,请纠正我.

Thanks a lot for elaborating your application flow and the logs. I understand now that your HTTP Request header 'content-type' is set to 'multipart/form-data'. I agree that for a web form to upload a file it is quite common to set content type as form-data and AWS API Gateway does support it. You would like to know if you could prevent UTF-8 encoding without changing the front end code. Please correct me if my understanding is wrong.

为了便于讨论,我想将HTTP请求和响应的故障排除方法分开.

For the ease of discussion, I would like to separate the approach of troubleshooting for the HTTP request and response.

请在API Gateway控制台的"API设置"页面中,将"multipart/form-data"添加为binaryMediaType列表中的值之一.您不必更改代码或HTTP请求或其任何标头.请注意,要处理API Gateway中的二进制媒体/数据,HTTP Request Content-Type标头必须与binaryMediaType列表中的值匹配.

Please add 'multipart/form-data' as one of the values in the binaryMediaType list in your "API settings page in the API Gateway console. You would not have to alter your code or HTTP request or any of it's headers. Kindly note to handle binary media/data in API Gateway, the HTTP Request Content-Type header must match the values in binaryMediaType list.

在您的用例中,如果要在请求响应中发送二进制媒体,请返回HTTP请求"Content-Type"和"Accept"标头,API的binaryMediaType值以及HTTP响应"Content"-Type"必须全部设置为"multipart/form-data".我尝试了上面的方法,它对Postman Client很有用.如果HTTP请求的内容类型"设置为多部分/表单数据",则Postman会自动设置边界"指令.因此,您只需在"binaryMediaType"列表中添加"multipart/form-data".请在下面查看我的HTTP请求:

In your use case, if you want to send the binary media back in a response for your request, the HTTP Request 'Content-Type' and 'Accept' headers, the binaryMediaType value of the API and the HTTP Response 'Content-Type' must all be set to 'multipart/form-data'. I tried the above and it worked for me with Postman Client. The 'boundary' directive is set up by Postman automatically if the HTTP Request 'Content-Type' is set to 'multipart/form-data'. Hence, you would have to only add 'multipart/form-data' in the 'binaryMediaType' list. Please have a look at my HTTP request, below:


POST /stg-with-logs HTTP/1.1
Host: <some-api-id>.execute-api.us-east-1.amazonaws.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Accept: multipart/form-data
Cache-Control: no-cache
Postman-Token: 123b64f9-5669-f794-b9df-34a7561e9708

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="File"; filename="archive.zip"
Content-Type: application/zip


------WebKitFormBoundary7MA4YWxkTrZu0gW--

对于来自API的响应:

我注意到在通过您的API网关日志时,未设置标头'isBase64Encoded'.请将其设置为true.如果将'isBase64Encoded'设置为true,API Gateway会自动解码HTTP响应正文中的所有base64编码的字符串.请在下面查看我的lambda的HTTP响应:

For the response from the API:

I noticed while going through your API Gateway Logs, the header 'isBase64Encoded' was not set. Kindly set that to true. API Gateway automatically decodes any base64-encoded string in the body of your HTTP response, if 'isBase64Encoded' is set to true. Please have a look at the HTTP Response from my lambda below:


(a6729f56-b245-45a4-9ac4-7e00b23c8957) Endpoint response body before transformations: 
{
    "isBase64Encoded": true,
    "statusCode": 200,
    "headers": {
        "Content-Type": "multipart/form-data",
        "Accpet": "multipart/form-data"
    },
    "body": "LS0tLS0tV2ViS2l0Rm9ybUJvdW5kYXJ5SmxkSW1aV1lHczlSTndPWQ0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJGaWxlIjsgZmlsZW5hbWU9ImFyY2hpdmUuemlwIg0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi96aXANCg0KUEsDBBQAAAAIAKF4kE9/Mo7/XgAAAJcAAAAaABwASGVsbG8tV29ybGQtNjY3MzMxNTI4MS50eHRVVAkAA8ZP910SUPdddXgLAAEEHZHreQTMewNxNY1BDgIxDAPvvIVPOY3SEC+9WCrfJ13EZWTNHKwKkzMmxIp5dpsnFMlqrjzBF/SKxCW2/8dl3ttGGjTqnkdMG+Wwj96jA3/YJsC2QF9iesuLUXPfv80KrpaVYeDjC1BLAQIeAxQAAAAIAKF4kE9/Mo7/XgAAAJcAAAAaABgAAAAAAAEAAACkgQAAAABIZWxsby1Xb3JsZC02NjczMzE1MjgxLnR4dFVUBQADxk/3XXV4CwABBB2R63kEzHsDcVBLBQYAAAAAAQABAGAAAACyAAAAAAANCi0tLS0tLVdlYktpdEZvcm1Cb3VuZGFyeUpsZEltWldZR3M5Uk53T1kNCkNvbnRlbnQtRGlzcG9zaXRpb246IGZvcm0tZGF0YTsgbmFtZT0iVGVzdCBEYXRhIg0KDQpUZXN0aW5nIEJvdW5kYXJ5IGluIG11bHRpcGFydC9mb3JtLWRhdGENCi0tLS0tLVdlYktpdEZvcm1Cb3VuZGFyeUpsZEltWldZR3M5Uk53T1ktLQ0K"
}

与此通信同时,我附上我的API Gateway Swagger文件和Lambda函数代码,以供您参考.该设置对我来说运行良好,我能够在发出HTTP请求时返回二进制有效负载.如果要在您的环境中进行测试,请在Swagger文件中设置适当的凭据和lambda uri.

Along with this correspondence I am attaching my API Gateway Swagger file and Lambda function code for your reference. The setup worked fine for me and I was able to return the binary payload upon making an HTTP Request. If you want to test it out in your environment, please set the appropriate credentials and lambda uri in the Swagger file.

希望这可以解决您的问题.但是,如果问题仍然存在,或者您还有其他问题,请再次与我们联系,我们将很乐意为您提供帮助.

Hope this addresses your concern. However, if the issue still persists or you have any further questions, please contact us again and I will be happy to assist you.

要查看此通信中包含的名为"binaryPost-stg-with-logs-oas30-apigateway.yaml,python-binary-response.py"的文件,请使用签名下方给出的大小写链接.

To see the file named 'binaryPost-stg-with-logs-oas30-apigateway.yaml,python-binary-response.py' included with this correspondence, please use the case link given below the signature.

最诚挚的问候,

Jyoti Prakash P.亚马逊网络服务

Jyoti Prakash P. Amazon Web Services

查看AWS Support知识中心,该知识库是由文章和视频组成的知识库,可以回答客户有关AWS服务的问题:

Check out the AWS Support Knowledge Center, a knowledge base of articles and videos that answer customer questions about AWS services: https://aws.amazon.com/premiumsupport/knowledge-center/?icmpid=support_email_category

这篇关于AWS apigateway是否会更改http正文?如何阻止它执行此操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆