2

我已经开始学习 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()
  }
}

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

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

4

1 回答 1

4

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

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);
    }
}
于 2013-09-16T10:42:36.960 回答