用户名和密码打开网址

时间:2013-09-16 10:16:46

标签: scala

我已经开始学习scala,我知道的唯一另一种语言是python。 我试图在scala中编写一个我用python编写的代码。 在该代码中,我必须打开一个xml格式的URL,需要用户名和 密码然后解析它并获取匹配字符串名称= 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中写的打开网址我仍然要弄清楚如何 使用用户名密码处理它我在互联网上搜索过相同的信息并且仍在使用 没找到我要找的东西。

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和获取字符串名称= ID的元素的任何帮助也欢迎

1 个答案:

答案 0 :(得分: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);
    }
}