gpt4 book ai didi

Scala HttpPost - 如何传递身份验证参数

转载 作者:行者123 更新时间:2023-12-03 21:31:17 25 4
gpt4 key购买 nike

- - - 更新
能够通过使用 UsernamePasswordCredentials 类来修复它
代码如下所示
val 客户端 = 新的 DefaultHttpClient
client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("user","password"));

我正在尝试对 Restful API 进行 HttpPost 调用,它需要一个用户名/密码,如何传递这些参数?我尝试了 2 种方法

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=真,内容类型:文本/html; charset=ISO-8859-1,缓存控制:必须重新验证,无缓存,无存储,内容长度: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))

最佳答案

你可以这样写,它在我的程序中有效

import java.util.Base64

httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder.encodeToString("[your-username]:[your-password]".getBytes))

关于Scala HttpPost - 如何传递身份验证参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com