使用Scala的HttpPost

时间:2019-06-13 17:47:30

标签: scala web-scraping http-post jsoup httpclient

我正在尝试使用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)
  }
}

有人可以告诉我我在这里想念什么吗?

1 个答案:

答案 0 :(得分:0)

因此,我尝试发布的API不会使用BasicCredentialsProvider中的用户名和密码。我必须在外部API链接后缀相同。现在可以工作。