scala - 使用 Scala 的 HttpPost
问题描述
我正在尝试使用 Scala 将 JSON 字符串发送到外部 API。无法得到适当的回应。
得到HTTP/1.1 400 Error
下面我的代码的响应。在 Postman 中尝试了同样的方法,它给出了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)
}
}
有人可以告诉我我在这里缺少什么吗?
解决方案
因此,我尝试发布的 API 不会从BasicCredentialsProvider
. 我必须在外部 API 链接后面加上相同的后缀。现在工作。
推荐阅读
- redux - Redux 工具包:如何从 thunk(createAsyncThunk) 调用另一个操作
- database - 即使在表级别增加了 autovacuum_freeze_max_age,也会为表的事务环绕触发 Autovacuum
- python - 根据房地产 ID 从数据框中提取唯一价格值
- c# - “不支持的媒体类型”,在 react-native 中发布请求时出现 415 错误
- composer-php - 找不到包裹 drush/drush
- kubernetes - Kubernetes:Deployment 和 Replica set 有什么区别?
- c++ - 现有软件包上的 Flutter Windows 支持
- c - 分配错误后释放内存 (realloc)
- macos - 如何在 Mac 上打开从终端到 PhpStorm 的路径?
- java - 将 Lagom 连接到 Amazon MSK (Kafka)