如何解决dialogflow身份验证问题

时间:2019-05-01 15:18:34

标签: java http dialogflow gcloud restful-authentication

我有一个dialogflow项目,试图通过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;

代码的要旨是简单地向我的dialogflow发送一条消息(“ Hello World!”),并获取我的代理的响应(代码可能有错误-当我无法获得该代码时,很难进行测试通过了此身份验证问题,因此请提供身份验证帮助,而不是代码错误)。

谢谢!

1 个答案:

答案 0 :(得分:0)

该页面上的说明假定您将使用The input程序生成当前有效的承载令牌,然后将其与HTTP标头一起发送。该页面说明了

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

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

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

相关问题