Search code examples
scalacurlpostxmlhttprequestapache-httpclient-4.x

Transforming a curl request (POST) with multipart/form-data into scala code


I have the following curl request that I am trying to implement in scala.

curl -u "username" -X POST "https://post_url.com" -H "Content-Type: multipart/form-data" -F "xmlRequest=@/home/@file.xml;type=text/xml"

I have tried the following but I get a bad request.

val client = new DefaultHttpClient()
val requestEntity = MultipartEntityBuilder.create().addBinaryBody("xmlRequest",
  new File("/home/@file.xml")).build()
val post = new HttpPost("https://post_url.com")
post.addHeader(BasicScheme.authenticate(new
      UsernamePasswordCredentials(username, password), "UTF-8", false))
post.addHeader("Content-Type", "multipart/form-data")
post.setEntity(requestEntity)
val response = client.execute(post)
println(response.getStatusLine)

Solution

  • I have been able to solve my problem by just using another addBinaryBody function.

      val client = new DefaultHttpClient()
      val requestEntity = MultipartEntityBuilder.create().addBinaryBody("xmlRequest",
      new File("/home/@file.xml"), ContentType.DEFAULT_BINARY, "").build()
      val post = new HttpPost("https://post_url.com")
      post.addHeader(BasicScheme.authenticate(new
      UsernamePasswordCredentials(username, password), "UTF-8", false))
      post.addHeader("Content-Type", "multipart/form-data")
      post.setEntity(requestEntity)
      val response = client.execute(post)
      println(response.getStatusLine)