Я работаю с функциями AWS Lambda, и у меня возникла проблема с отправкой POST-запроса в функцию Lambda.
Я обнаружил, что с помощью PostMan я могу добавить заголовок приложения/json Content-Type, и все работает так, как должно — код видит запрос и обрабатывает его правильно.
Я запустил удаленный отладчик AWS Lambda и вижу, что объект запроса имеет значение null, когда Отсутствует заголовок приложения/json типа контента.
Есть ли способ добавить этот заголовок в мой запрос из платформы AWS Lambda?
Я делаю что-то не так?
Я создал класс, представляющий объект, который хочу передать, в формате JSON.
public class Order {
public int id;
public String itemName;
public int quantity;
public Order() {
}
public Order(int id, String itemName, int quantity) {
this.id = id;
this.itemName = itemName;
this.quantity = quantity;
}
}
Если я просто отправлю JSON без приложения Content-Type/json, код выдаст исключение JSON, как показано ниже:
2026-01-27T13:58:59.678Z
argument "content" is null: java.lang.IllegalArgumentException
java.lang.IllegalArgumentException: argument "content" is null
at com.fasterxml.jackson.databind.ObjectMapper._assertNotNull(ObjectMapper.java:4980)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3739)
at helloworld.CreateOrderLambda.createOrder(CreateOrderLambda.java:13)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
С помощью PostMan я вставил заголовок Content-Type application/json, и запрос POST прошел успешно.
Мой код Lambda Java показан ниже:
package helloworld;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CreateOrderLambda {
public APIGatewayProxyResponseEvent createOrder(APIGatewayProxyRequestEvent request)
throws JsonMappingException, JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Order order = objectMapper.readValue(request.getBody(), Order.class);
String responseMessage = String.format("Order created: ID=%d, Item=%s, Quantity=%d", order.id, order.itemName, order.quantity);
return new APIGatewayProxyResponseEvent().withStatusCode(200).withBody(responseMessage);
}
}
Шаблон.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
scratch
Sample SAM Template for scratch
# More info about Globals: https://github.com/awslabs/serverless-a ... lobals.rst
Globals:
Function:
Timeout: 20
MemorySize: 512
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-a ... ssfunction
Properties:
CodeUri: HelloWorldFunction
Handler: helloworld.CreateOrderLambda::createOrder
Runtime: java25
Architectures:
- x86_64
MemorySize: 512
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-a ... ent-object
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-a ... -31.md#api
Properties:
Path: /order
Method: POST
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-a ... es.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}/Prod/order/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
Подробнее здесь: https://stackoverflow.com/questions/798 ... he-request
AWS Lambda не может отправить POST json без заголовка application/json в запросе ⇐ JAVA
Программисты JAVA общаются здесь
1769538784
Anonymous
Я работаю с функциями AWS Lambda, и у меня возникла проблема с отправкой POST-запроса в функцию Lambda.
Я обнаружил, что с помощью PostMan я могу добавить заголовок приложения/json Content-Type, и все работает так, как должно — код видит запрос и обрабатывает его правильно.
Я запустил удаленный отладчик AWS Lambda и вижу, что объект запроса имеет значение null, когда Отсутствует заголовок приложения/json типа контента.
Есть ли способ добавить этот заголовок в мой запрос из платформы AWS Lambda?
Я делаю что-то не так?
Я создал класс, представляющий объект, который хочу передать, в формате JSON.
public class Order {
public int id;
public String itemName;
public int quantity;
public Order() {
}
public Order(int id, String itemName, int quantity) {
this.id = id;
this.itemName = itemName;
this.quantity = quantity;
}
}
Если я просто отправлю JSON без приложения Content-Type/json, код выдаст исключение JSON, как показано ниже:
2026-01-27T13:58:59.678Z
argument "content" is null: java.lang.IllegalArgumentException
java.lang.IllegalArgumentException: argument "content" is null
at com.fasterxml.jackson.databind.ObjectMapper._assertNotNull(ObjectMapper.java:4980)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3739)
at helloworld.CreateOrderLambda.createOrder(CreateOrderLambda.java:13)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
С помощью PostMan я вставил заголовок Content-Type application/json, и запрос POST прошел успешно.
Мой код Lambda Java показан ниже:
package helloworld;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CreateOrderLambda {
public APIGatewayProxyResponseEvent createOrder(APIGatewayProxyRequestEvent request)
throws JsonMappingException, JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Order order = objectMapper.readValue(request.getBody(), Order.class);
String responseMessage = String.format("Order created: ID=%d, Item=%s, Quantity=%d", order.id, order.itemName, order.quantity);
return new APIGatewayProxyResponseEvent().withStatusCode(200).withBody(responseMessage);
}
}
Шаблон.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
scratch
Sample SAM Template for scratch
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 20
MemorySize: 512
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: HelloWorldFunction
Handler: helloworld.CreateOrderLambda::createOrder
Runtime: java25
Architectures:
- x86_64
MemorySize: 512
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
Variables:
PARAM1: VALUE
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /order
Method: POST
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}/Prod/order/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
Подробнее здесь: [url]https://stackoverflow.com/questions/79877386/aws-lambda-cannot-post-json-without-application-json-header-in-the-request[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия