从java中的Lambda函数调用外部Rest API

问题描述 投票:0回答:1

我正在尝试编写一个 lambda 函数,该函数从 lex 输入获取信息,并调用 Rest api,将该信息作为参数传递,返回一个字符串,然后我想将其作为响应发送给 lex。在 Eclipse 中运行时它按预期工作,但是当我将 jar 上传到亚马逊 lambda 时,它没有给出错误,但输出字符串为空。

public class LambdaFunctionHandler implements RequestHandler<Map<String,Object>, Object> {


@Override
public Object handleRequest(Map<String,Object> input, Context context) {

    ValidationHook.LexRequest lexRequest= LexRequestFactory.createLexRequest(input);
    String orgbotcommand = lexRequest.getCommand()+"%20"+lexRequest.getType()+"%20"+lexRequest.getNew_variable();
    lexRequest.setOrgbotcommand(orgbotcommand);

    try {
        URL url = new URL("http://localhost:8080/mindtuit/execute?command="+orgbotcommand);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            lexRequest.setResponse(output);

        }
        System.out.println(lexRequest.getResponse());

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

      }



    String content = String.format("command recieved by %s is %s,response is %s ",lexRequest.getBotName(),lexRequest.getOrgbotcommand(),lexRequest.getResponse());

    Message message = new Message("PlainText",content);
    DialogAction dialogAction = new DialogAction("Close", "Fulfilled", message );
    System.out.println(dialogAction);

    return new LexRespond(dialogAction);
}

}

java rest aws-lambda amazon-lex
1个回答
0
投票

使用 ngrok 并为应用程序运行端口生成 http url。

© www.soinside.com 2019 - 2024. All rights reserved.