使用Scala的HttpPost
我正在尝试使用Scala将JSON字符串发送到外部API。无法得到正确的回应 正在获取HTTP/1.1400错误作为下面我的代码的响应。在《邮递员》中尝试了同样的方法,它给出了使用Scala的HttpPost,scala,web-scraping,http-post,jsoup,httpclient,Scala,Web Scraping,Http Post,Jsoup,Httpclient,我正在尝试使用Scala将JSON字符串发送到外部API。无法得到正确的回应 正在获取HTTP/1.1400错误作为下面我的代码的响应。在《邮递员》中尝试了同样的方法,它给出了200 OK结果 import org.apache.http.auth.{AuthScope, UsernamePasswordCredentials} import org.apache.http.client.methods.HttpPost import org.apache.http.entity.StringE
200 OK
结果
import org.apache.http.auth.{AuthScope, UsernamePasswordCredentials}
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.{BasicCredentialsProvider, HttpClientBuilder}
import org.scalatest.{FunSpec, Matchers}
class MySpec extends FunSpec with Matchers {
it("should return 200") {
val extApi = "<external_api>"
val extApiResponse = doExtApiPost(extApi)
assert(extApiResponse.getStatusLine().getStatusCode().equals(200))
}
private def doExtApiPost(extApi: String) = {
val httpPost = new HttpPost(extApi)
val jsonString =
"""{
|"field1": "<field1_info>",
|"field2": "<field2_info>",
|"field3": "<field3_info>"
|}""".stripMargin
httpPost.setEntity(new StringEntity(jsonString))
httpPost.setHeader("Accept", "application/json")
httpPost.setHeader("Content-type", "application/json")
val username = "my_username"
val password = "my_password"
val credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(username, password)
)
val httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build()
httpClient.execute(httpPost)
}
}
import org.apache.http.auth.{AuthScope,UsernamePasswordCredentials}
导入org.apache.http.client.methods.HttpPost
导入org.apache.http.entity.StringEntity
导入org.apache.http.impl.client.{BasicCredentialsProvider,HttpClientBuilder}
导入org.scalatest.{FunSpec,Matchers}
类MySpec使用匹配器扩展了FunSpec{
它(“应该返回200”){
val extApi=“”
val extApiResponse=doExtApiPost(extApi)
断言(extApiResponse.getStatusLine().getStatusCode().equals(200))
}
私有def doExtApiPost(extApi:String)={
val httpPost=新的httpPost(extApi)
val jsonString=
"""{
|“字段1”:“,
|“字段2”:“,
|“字段3”:”
|}“.stripMargin”
setEntity(新的StringEntity(jsonString))
setHeader(“接受”、“应用程序/json”)
setHeader(“内容类型”、“应用程序/json”)
val username=“我的用户名”
val password=“我的密码”
val credentialsProvider=new BasicCredentialsProvider()
credentialsProvider.setCredentials(
任何,
新用户名密码凭据(用户名、密码)
)
val httpClient=HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider.build())
httpClient.execute(httpPost)
}
}
有人能告诉我这里缺少什么吗?所以我试图发布的API没有从
BasicCredentialsProvider
获取用户名和密码。我必须在外部API链接后面加上相同的后缀。现在可以工作了。你已经有了base64EncodedDoc
,为什么你还需要在下面的文章中发表文章呢?因为外部API需要这样做。