------更新 能够使用UsernamePasswordCredentials类来修复它 代码如下所示 val client = new 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,Content-Type:text / html; charset = ISO-8859-1,Cache-Control:必须重新验证,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))
答案 0 :(得分:0)
您可以这样编写,它可以在我的程序中工作
import java.util.Base64
httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder.encodeToString("[your-username]:[your-password]".getBytes))
答案 1 :(得分:0)
DefaultHttpClient
已过时。您应该改用BasicCredentialsProvider
。下面的示例代码:
val username = "your_username"
val password = "your_password"
val credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(username, password)
)
val httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build()
答案 2 :(得分:0)
此处的授权标头应按以下方式计算:
httpPost.addHeader("Authorization", "Basic " + Base64.getEncoder.encodeToString("[your-username]:[your-password]".getBytes))
它应该是getEncoder(),而不是getUrlEncoder()。