簡體   English   中英

從 Java 中的 Lambda 函數調用外部 Rest API

[英]Calling external Rest API from a Lambda function in java

我正在嘗試編寫一個 lambda 函數,該函數從 lex 輸入中獲取信息,並調用一個 rest api,將該信息作為參數傳遞,返回一個字符串,然后我想將其作為響應發送給 lex。 它在 Eclipse 中運行時按預期工作,但是當我將 jar 上傳到 amazon 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);
}

}

使用 ngrok 並為應用程序運行端口生成一個 http url。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM