如何使用JAVA / Scala从公共URL下载视频[关闭]

nnsrf1az  于 5个月前  发布在  Scala
关注(0)|答案(1)|浏览(41)

已关闭。此问题需要更多focused。目前不接受回答。
**要改进此问题吗?**更新此问题,使其仅针对editing this post的一个问题。

昨天就关门了。
Improve this question
我正在尝试从微软的sharepoint下载一个视频,网址已经提供给“任何人”,它可以在匿名浏览器窗口中工作。我也使用python脚本在我的本地下载它。
当我尝试使用Scala / Java时也是一样,它失败了,并出现403 - Forbidden错误。这是因为我认为服务器正在尝试重定向,而Java / Scala默认情况下在HttpUrlConnection中选择了它,并对其进行了调用。在错误消息中,我可以看到公司的内部URL,而不是我最初在代码中使用的公共URL。
1.我试着把下面的属性,因为有人建议它将绕过ssl验证的下载。但当我这样做,它只下载了41 Kb价值的页面说登录到微软。

connection.setRequestProperty(
      "User-Agent",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36")

字符串
1.我尝试使用SSL验证通过使用:https://tutoref.com/how-to-disable-ssl-certificat-validation-in-java/,但它不工作。

问题:

我怎么能从这个链接下载同样的文件,而Python可以下载,而Java / Scala却不行?Python和Scala / Java在提取数据的方式上有什么区别?

正在运行的Python脚本

import requests as req

asset_ext = '.mp4'
asset_name = 'test_asset'
local_file_name =  '/tmp/' + asset_name+asset_ext
print("Downloading file:%s"%local_file_name)
path_to_asset_file = 'https://my-URL'

r = req.get(path_to_asset_file, stream = True)

with open(local_file_name, 'wb') as f:
    for chunk in r.iter_content(chunk_size = 1024*1024):
        if chunk:
            f.write(chunk)
            
print("%s downloaded!\n"%local_file_name)

Scala代码不起作用

def fileDownloader(url: String, filename: String) = {
    val urlObj = new URL(url)

    SSLFix.execute()
    val connection = urlObj.openConnection().asInstanceOf[HttpURLConnection]
    connection.setRequestProperty(
      "User-Agent",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36")
    connection.setConnectTimeout(5000)
    connection.setReadTimeout(5000)
    connection.connect()

    if (connection.getResponseCode >= 400)
      println("error = " + connection.getResponseMessage)
    else
      urlObj #> new File(filename) !!
  }

SSLFix类是给定链接中的SSL验证绕过类。

def downloadFile(url: String, filePath: String): Option[File] = {
    val outputStream = new ByteArrayOutputStream()

    try {
      val chunk = new Array[Byte](4096)

      SSLFix.execute()
      val connection = new URL(url).openConnection()

      connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36")

      val stream = connection.getInputStream
      var bytesRead = stream.read(chunk)
      while (bytesRead > 0) {
        outputStream.write(chunk, 0, bytesRead)
        bytesRead = stream.read(chunk)
      }

      outputStream.flush()

      val outputFile = new File(filePath)
      Files.write(outputFile.toPath, outputStream.toByteArray)

      Some(outputFile)
    } catch {
      case e: IOException =>
        e.printStackTrace()
        None
    } finally {
      outputStream.close()
    }
  }

e5njpo68

e5njpo681#

你必须分析服务器端的行为来找出缺少了什么,但是你在这里问,所以我假设这对你来说是不可见的。
由于您已经有了工作客户端,因此最好的办法是分析传输的数据。

相关问题