【问题标题】:Url open with username and password使用用户名和密码打开网址
【发布时间】:2013-09-16 10:16:46
【问题描述】:

我已经开始学习 scala ,我唯一知道的其他语言是 python。 我正在尝试在我用 python 编写的 scala 中编写代码。 在该代码中,我必须打开一个 xml 格式的 url,它需要用户名和 密码,然后解析它并获取与字符串 name=ID 匹配的元素

这是我的python代码

import urllib2

theurl = 'Some url'
username = 'some username'
password = 'some password'
# a great password

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for  urls
# for which `theurl` is a super-url

authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler

opener = urllib2.build_opener(authhandler)

urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.

pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us


##########################################################################

from xml.dom.minidom import parseString

file = pagehandle

#convert to string:
data = file.read()
#close file because we dont need it anymore:
file.close()
#parse the xml you downloaded
dom = parseString(data)
#retrieve the first xml tag (<tag>data</tag>) that the parser finds with name tagName:
xmlData=[]
for s in dom.getElementsByTagName('string'):
    if s.getAttribute('name') == 'ID':
        xmlData.append(s.childNodes[0].data)
print xmlData

这就是我在 scala 中为打开一个 url 而写的内容我仍然想知道如何 用我在互联网上搜索过的用户名密码处理它 没有得到我要找的东西。

object URLopen {
  import java.net.URL
  import scala.io.Source.fromURL
  def main(arg: Array[String]){
    val u = new java.net.URL("some url")
    val in = scala.io.Source.fromURL(u) 
    for (line <- in.getLines)
      println(line)
    in.close()
  }
}

有人可以帮我处理用用户名密码打开的网址吗 或者告诉我从哪里可以学习如何做到这一点? 在 python 中,我们有 docs.python.org/library/urllib2.html 在那里我可以了解各种模块以及如何使用它们。 scala 也有链接吗?

PS:也欢迎任何有关解析 xml 和获取字符串 name= ID 的元素的帮助

【问题讨论】:

标签: scala


【解决方案1】:

您所描述的是基本身份验证,在这种情况下您需要:

import org.apache.commons.codec.binary.Base64;

object HttpBasicAuth {
   val BASIC = "Basic";
   val AUTHORIZATION = "Authorization";

   def encodeCredentials(username: String, password: String): String = {
      new String(Base64.encodeBase64String((username + ":" + password).getBytes));
   };

   def getHeader(username: String, password: String): String = 
      BASIC + " " + encodeCredentials(username, password);
};

然后将其添加为请求标头。

import scala.io.Source
import java.net.URL

object Main extends App {
    override def main(args: Array[String]) {
      val connection = new URL(yoururl).openConnection
      connection.setRequestProperty(HttpBasicAuth.AUTHORIZATION, HttpBasicAuth.getHeader(username, password);
      val response = Source.fromInputStream(connection.getInputStream);
    }
}

【讨论】:

  • 感谢flavian的回复,我的用户名和密码在哪里放,也可以从哪里了解这些模块以及你用过的如何使用它们
  • 它说,对象 apache 不是包 org import org.apache.commons.codec.binary.Base64 的成员;
  • 我安装了 commons-codecs-1.2.jar,当我再次运行它时,它显示以下错误值 encodeBase64String is not a member of object org.apache.commons.codec.binary.Base64 Base64。 encodeBase64String((用户名 + ":" + 密码).getBytes); ^ 当我看到其中存在对象时,它们是 encodeBase64 的变体,当我使用 encodeBase64 时,以下错误来自类型不匹配;找到:Array[Byte] required: String Base64.encodeBase64((username + ":" + password).getBytes); ^
  • 我知道我应该先阅读教程,但我的导师告诉我先将代码转换为 scala 并以这种方式学习
猜你喜欢
  • 2015-05-22
  • 2021-03-15
  • 1970-01-01
  • 2012-06-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 2010-12-26
相关资源
最近更新 更多