使用Scala上传文件并设置标头

时间:2017-02-17 07:37:41

标签: scala file-upload http-headers hockeyapp

我一直在玩文件上传到曲棍球应用程序已经有一段时间了。我设法让这个东西现在运行,但我撞到了下一堵墙。我设置的标题无法识别。你可以在这里找到整个代码:https://github.com/firegate666/unitycloudbuildhockeyappscala但受影响的类是这个类:

package de.firegate.tools

import java.io.File
import java.net.URI
import org.apache.http.client.methods.{HttpPost, CloseableHttpResponse}
import org.apache.http.client.protocol.HttpClientContext
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.entity.mime.content.{StringBody, FileBody}
import org.apache.http.entity.ContentType
import org.apache.http.util.EntityUtils
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.apache.http.impl.client.HttpClients
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try

object Uploader {

  lazy val httpClient = {
    val connManager = new PoolingHttpClientConnectionManager()
    HttpClients.custom().setConnectionManager(connManager).build()
  }

  def run(uri: URI, file: File, properties: Map[String, String], header: Map[String, String]): Future[Try[String]] = {
    import ExecutionContext.Implicits.global

    Future {
      Try({
        // Create the entity
        val reqEntity = MultipartEntityBuilder.create()

        // Attach the file
        reqEntity.addPart("ipa", new FileBody(file))

        for ((key, value) <- properties) {
          reqEntity.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN))
        }

        // Create POST request
        val httpPost = new HttpPost(uri)
        httpPost.setEntity(reqEntity.build())

        for ((name, value) <- properties) {
          httpPost.addHeader(name, value)
        }

        println(httpPost.getAllHeaders.flatMap(x => x.getName + ":" + x.getValue))

        // Execute the request in a new HttpContext
        val ctx = HttpClientContext.create()
        val response: CloseableHttpResponse = httpClient.execute(httpPost, ctx)

        // Read the response
        val entity = response.getEntity
        val result = EntityUtils.toString(entity)

        // Close the response
        if (response != null) response.close()

        result
      })
    }
  }
}

这就是它的名称

val uri = new URI(UnityCloudBuildOptions.hockeyAppUrl)
val properties = Map(
  "status" -> "2", // to make the version available for download
  "notes" -> "Automated release triggered from Unity Cloud Build.",
  "notes_type" -> "0",
  "notify" -> "0"
)

val header = Map(
  "X-HockeyAppToken" -> UnityCloudBuildOptions.hockeyappAPIKey,
  "Accept" -> "application/json"
)

val futureResponse = Uploader.run(uri, file, properties, header)

上传很好,但最终曲棍球应用程序抱怨丢失凭据,但标题已设置。

08:29:16.315 Upload finished {"errors":{"credentials":["no api token"]}}

0 个答案:

没有答案