------更新能够通过使用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))
你可以像这样写,它在我的程序中有效
import java.util.Base64
httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder.encodeToString("[your-username]:[your-password]".getBytes))
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()