首页 > 解决方案 > 使用 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)
  }
}

有人可以告诉我我在这里缺少什么吗?

标签: scalaweb-scrapinghttp-postjsouphttpclient

解决方案


因此,我尝试发布的 API 不会从BasicCredentialsProvider. 我必须在外部 API 链接后面加上相同的后缀。现在工作。


推荐阅读