Search code examples
scalaweb-scrapinghttp-postjsouphttpclient

HttpPost using Scala


I am trying to send a JSON string to an external API using Scala. Not able to get proper response.

Getting HTTP/1.1 400 Error as the response for my code below. Tried the same in Postman, it's giving 200 OK result.

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)
  }
}

Can someone please tell me what I am missing here?


Solution

  • So the API I am trying to post, doesn't take username and password from BasicCredentialsProvider. I had to suffix the external API link with the same. Works now.