如何使用带标题

时间:2016-05-09 06:13:22

标签: ruby faraday

我在尝试使用法拉第上传文件到网络服务时遇到问题。

conn = Faraday.new('http://myapi') do |f|
  f.request :multipart
  f.adapter Faraday.default_adapter
end

payload = Faraday::UploadIO.new(file_io, 'application/pdf') 

conn.post '/upload', payload

java api接受POST'Content-Type' => 'multipart/form-data'。该请求应该发送带有所需边界的文件。它不是。 拦截请求时,它会将标头设置为x-url encoded。如果标题预设为Content-Type,则边界不会被法拉第添加。

API抛出,

  

2016-05-09 11:36:03,068 [1] [e02b7381] [jetty-139] INFO   com.fm.rest.services.interceptor.RequestLoggingInInterceptor -   索取信息:     POST http://localhost:8080/api/projects/1/files/f719137f-702a-4801-9654-95f5a58d78f2 ISO-8859-1 multipart / form-data标题:   {接受= [ / ],   编码接受= [gzip的; Q = 1.0,放气; Q = 0.6,身份; Q = 0.3],   connection = [close],Content-Length = [217115],   content-type = [multipart / form-data],Host = [localhost:8080],   User-Agent = [Ruby],X-Newrelic-Id = [12YHU123wsC123wE =],   X-NewRelic的-事务= [P9TDFcABCAEEVQ8JFTs =]}   2016-05-09 11:36:03,072 [1] [e02b7381] [码头-139]警告   org.apache.cxf.phase.PhaseInterceptorChain - Interceptor for   {http://services.rest.fm.api.com/} DirectoryRestService已抛出   异常,现在展开org.apache.cxf.interceptor.Fault:不行   从消息中确定边界!在   org.apache.cxf.interceptor.AttachmentInInterceptor.handleMessage(AttachmentInInterceptor.java:66)

我无法在帖子请求中设置标题

1 个答案:

答案 0 :(得分:0)

问题不是将法拉第上传器io包装在哈希

payload = { :file => Faraday::UploadIO.new(file, 'application/pdf') }

这解决了法拉第未设置正确标题的问题。 Faraday :: Connection帖子的最后一个参数是从docs

看到的标题
header = {'Authorization': 'Basic =A123CD'}
conn.post url, payload, header