【发布时间】:2017-01-27 15:00:11
【问题描述】:
--------更新 能够通过使用 UsernamePasswordCredentials 类来修复它 代码如下所示 val 客户端 = 新的 DefaultHttpClient client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("user","password"));
我正在尝试对 Restful API 进行 HttpPost 调用,它需要用户名/密码,如何传递这些参数?我尝试了两种方法
post.addHeader("Username","user")
post.addHeader("Password","clear pwd")
and
post.addHeader("Authorization","Basic base64encoded username:password")
没有任何效果,我得到的响应文本为
响应文本 = HTTP/1.1 401 未经授权 [WWW-Authenticate: Digest realm="API Realm", domain="/default-api", nonce="pOxqalJKm5L5QXiphgFNmrtaJsh+gU", algorithm=MD5, qop="auth" , stale=true, 内容类型: text/html; charset=ISO-8859-1, Cache-Control: must-revalidate,no-cache,no-store, Content-Length: 311] org.apache.http.conn.BasicManagedEntity@5afa04c
下面是我的代码
val url = "http://restapi_url";
val post = new HttpPost(url)
//post.addHeader("Authorization","Basic QWBX3VzZXI6Q0NBQGRidHMxMjM=")
post.addHeader("Username","user_user")
post.addHeader("Password","clear pwd")
post.addHeader("APPLICATION_NAME","DO")
val fileContents = Source.fromFile("input.xml").getLines.mkString
post.setHeader("Content-type", "application/xml")
post.setEntity(new StringEntity(fileContents))
val response = (new DefaultHttpClient).execute(post)
println("Response Text = "+response.toString())
// print the response headers
println("--- HEADERS ---")
response.getAllHeaders.foreach(arg => println(arg))
【问题讨论】:
标签: scala authentication http-post