【问题标题】:How to fix dialogflow authentication issue如何修复对话流身份验证问题
【发布时间】:2019-09-20 03:42:11
【问题描述】:

我有一个对话流项目,我正试图通过一个 rest 调用从 Java 访问它。 它给了我一个身份验证问题。 我已按照所有在线说明(以及许多论坛建议)无济于事。

我已尝试按照此处的说明生成密钥 json:

https://dialogflow.com/docs/reference/v2-auth-setup

并按照描述设置我的环境变量,但似乎没有任何效果。 我检查了我的 projectID,并且正在使用环境变量在同一台机器上运行,并且双重、三重和四重检查了它的名称和位置,但我仍然收到以下错误:

java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode

这是我的代码(虽然它是一个 REST 调用,所以我不知道它是否如此相关):

String url = https://dialogflow.googleapis.com/v2/projects/MYPROJECT/agent/sessions/SESSION_NUM:detectIntent
URL url = new URL(full_url);
String inText = "Hello World";
String outText = "";
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try {
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // set body of http post
    Map<String,String> arguments = new HashMap<>();
    JSONObject inTextJsn = new JSONObject();
    inTextJsn.append("text",inText);
    inTextJsn.append("languageCode","en");
    JSONObject fieldJsn = new JSONObject();
    fieldJsn.append("text", inTextJsn);
    arguments.put("queryInput", fieldJsn.toString());
    StringJoiner sj = new StringJoiner("&");
    for(Map.Entry<String,String> entry : arguments.entrySet())
        sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                + URLEncoder.encode(entry.getValue(), "UTF-8"));

    // post http post as bytes
    byte[] bytes_out = sj.toString().getBytes(StandardCharsets.UTF_8);
    con.setFixedLengthStreamingMode(bytes_out.length);
    con.connect();
    try (OutputStream os = con.getOutputStream()) {
        os.write(bytes_out);
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(),
            "UTF-8"));

    // read all lines to a string
    String line;
    String response = "";
    while ((line = reader.readLine()) != null) {
        response += line;
    }


    JSONObject responseJsn = new JSONObject(response);
    outText = responseJsn.get("fulfillmentText").toString();

} catch (Exception e) {
    System.err.println(e);
} finally {
    con.disconnect();
}

return restResponse;

代码的要点是简单地向我的对话流发送一条消息(“Hello World!”),然后取回我的代理的响应(代码可能有错误 - 当我无法获得时,有点难以测试通过了这个认证问题,所以请帮助认证,而不是代码错误)。

谢谢大家!

【问题讨论】:

    标签: java http dialogflow-es gcloud restful-authentication


    【解决方案1】:

    该页面上的说明假设您将使用gcloud 程序生成当前有效的不记名令牌,然后将其与 HTTP 标头一起发送。该页面说明了

    您的代码似乎根本没有生成 Authorization HTTP 标头,这就是您遇到错误的原因。

    由于您使用的是 Java,因此您应该查看 google-auth-library-java library,它会为您提供生成令牌的工具,您需要在 Authorization 标头中提供。

    您可能还想查看google-cloud-java library。这包含 Java 类,用于直接对 Dialogflow 执行操作,而不是自己编写 REST/HTTP 调用。 (但是,对于 Dialogflow,它仍处于 Alpha 级别,因此可能不稳定或向前兼容。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2020-10-04
      相关资源
      最近更新 更多