首页 > 解决方案 > 使用 scala 从 IntelliJ 连接到 Azure CosmosDB 时无法绕过代理

问题描述

我正在尝试使用 scala 语言从 intelliJ 连接到 azure cosmos DB。

当我从家庭网络连接笔记本电脑时,我能够从数据库中获取数据。但是当我从办公室网络连接笔记本电脑时出现超时错误。这似乎是一些代理问题,所以我在 intelliJ 中配置了代理设置,如下所示。

在此处输入图像描述

我试图从代理设置页面测试我的连接,但它抛出如下错误。

Problem with connection: Request failed with status code 401

我试图从浏览器中打开它并收到以下错误。

{"code":"Unauthorized","message":"Required Header authorization is missing. Ensure a valid Authorization token is passed.\r\nActivityId: af2d771f-25a3-494a-90dd-b33cd66104e2, Microsoft.Azure.Documents.Common/2.5.1"}

下面是我尝试过的 intelliJ 代码,该代码有效。

mport org.apache.spark.sql.SparkSession
import com.microsoft.azure.cosmosdb.spark.schema._
import com.microsoft.azure.cosmosdb.spark._
import com.microsoft.azure.cosmosdb.spark.config.Config
import org.apache.log4j.Logger

object DeleteData {
  /* Get the logger */
  val log = Logger.getLogger(getClass.getName)

  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder().master("local").appName("DeleteData").getOrCreate()

    // Configure connection to your collection
    val readConfig = Config(Map(
      "Endpoint" -> "https://***.documents.azure.com:443/",
      "Masterkey" -> "***",
      "Database" -> "ConnectivityDB",
      "Collection" -> "historicData",
      "ConnectionMode" -> "Gateway",
      "SamplingRatio" -> "1.0",
      "query_custom" -> "SELECT c.NUM from c where c._ts = 1564566440"
    ))
    // Connect via azure-cosmosdb-spark to create Spark DataFrame
    val docs = spark.read.cosmosDB(readConfig)
    println("Total Count: " +docs.count())
    docs.show(5)

    spark.stop()
  }
}

有什么方法可以绕过从 intelliJ 连接到 cosmos DB 的代理?

标签: scalaazureintellij-ideaazure-cosmosdbazure-cosmosdb-sqlapi

解决方案


恐怕 IntelliJ 代理设置不会影响您的代码,您可以尝试通过 Fiddler 工具捕获请求。

也许您可以在代码中设置代理设置。请参阅此链接

import java.net.Authenticator
import java.net.PasswordAuthentication

class ProxyAuthenticator(user: String, password: String) extends Authenticator {

  def this() = this("default_user_name", "default_password")

  override def getPasswordAuthentication(): PasswordAuthentication = {
    return new PasswordAuthentication(user, password.toCharArray());
  }
}

推荐阅读