多部分POST请求Google Glass [英] Multipart POST request Google Glass

查看:107
本文介绍了多部分POST请求Google Glass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用多部分编码添加到我的时间轴上的附件。我一直在做以下事情:

I am trying to add an attachment to my timeline with the multipart encoding. I've been doing something like the following:

req = urllib2.Request(url,data={body}, header={header})
resp = urllib2.urlopen(req).read()

它已经适用于application / json。但是,我不知道如何格式化多部分的正文。我也使用了一些库:请求和海报,并且由于某种原因他们都返回401。

And it has been working fine for application/json. However, I'm not sure how to format the body for multipart. I've also used some libraries: requests and poster and they both return 401 for some reason.

如何使用libary(最好是插件 - urlib2)或urllib2本身(像上面的代码块)?

How can I make a multipart request either with a libary(preferably a plug-in to urllib2) or with urllib2 itself (like the block of code above)?

编辑:
我也想这样能够支持 https的mirror-api视频/ vnd.google-glass.stream-url ://developers.google.com/glass/timeline

此处使用海报库的请求是代码:

For the request using poster library here is the code:

register_openers()
datagen, headers = multipart_encode({'image1':open('555.jpg', 'rb')})

这里使用的是重新设置:

Here it is using requets:

headers = {'Authorization' : 'Bearer %s' % access_token}
files = {'file': open('555.jpg', 'rb')}
r = requests.post(timeline_url,files=files, headers=headers)

返回401 - >标题

Returns 401 -> header

谢谢


Thank you

推荐答案

这是我做的,python客户端库如何做。

This is how I did it and how the python client library does it.

from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.mime.image import MIMEImage

mime_root = MIMEMultipart('related', '===============xxxxxxxxxxxxx==')
headers= {'Content-Type': 'multipart/related; '
          'boundary="%s"' % mime_root.get_boundary(),
          'Authorization':'Bearer %s' % access_token}
setattr(mime_root, '_write_headers', lambda self: None)
#Create the metadata part of the MIME
mime_text = MIMENonMultipart(*['application','json'])
mime_text.set_payload("{'text':'waddup doe!'}")
print "Attaching the json"
mime_root.attach(mime_text)

if method == 'Image':
    #DO Image
    file_upload = open('555.jpg', 'rb')
    mime_image = MIMENonMultipart(*['image', 'jpeg'])
    #add the required header
    mime_image['Content-Transfer-Encoding'] = 'binary'
    #read the file as binary
    mime_image.set_payload(file_upload.read())
    print "attaching the jpeg"
    mime_root.attach(mime_image)

elif method == 'Video':
    mime_video = MIMENonMultipart(*['video', 'vnd.google-glass.stream-url'])
    #add the payload
    mime_video.set_payload('https://dl.dropboxusercontent.com/u/6562706/sweetie-wobbly-cat-720p.mp4')
    mime_root.attach(mime_video)

Mark Scheel我用你的视频进行测试:)谢谢。

Mark Scheel I used your video for testing purposes :) Thank you.

这篇关于多部分POST请求Google Glass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆