在Microsoft Word 2011 for OSX中通过POST发送和接收数据 [英] Sending and receiving data via POST in Microsoft Word 2011 for OSX

查看:85
本文介绍了在Microsoft Word 2011 for OSX中通过POST发送和接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试移植一个我们在Windows上为MS Word工作的宏,该宏使用一个网站生成一个方程式图像并返回该图像以插入到文档中.当前(在Windows上运行)的调用如下.当我在OSX中使用相同的调用时,收到一条错误429,指出"ActiveX组件无法创建对象".

I am trying to port a macro that we have working for MS Word on Windows that uses a website to generate an equation image and returns that image for insertion into a document. The current (working on Windows) call is below. When I use the same call in OSX, I receive an error 429 stating "ActiveX component can't create object".

' Create an xmlhttp object.
Set w_page = CreateObject("Microsoft.XMLHTTP")

' Open the connection to the remote server.
w_page.Open "POST", WebAdd, False

' Indicate that the body of the request contains form data
w_page.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

' Actually send the request and return the data:
Font_Size = ComboFontSize.Value
w_page.Send "formula=" & Font_Size & "." & Latex_Str

Set w_page = CreateObject("Microsoft.XMLHTTP")语句上生成错误.我尝试了几种替代方法,例如:

The error is generated on the Set w_page = CreateObject("Microsoft.XMLHTTP") statement. I have tried a couple of alternate methods such as:

Set w_page = CreateObject("MSXML2.ServerXMLHTTP")

Set w_page = CreateObject("WinHttp.WinHttpRequest.5.1")

但是会产生相同的错误.请帮助我找到在OSX Word 2011中发送POST的正确方法.

But the same error is generated. Please help me find the correct way of sending POSTs in OSX Word 2011.

对于感兴趣的任何人,可以在 GitHub 上找到该项目.

For anybody interested, the project is available on GitHub.

非常感谢!

编辑:我找到了

EDIT: I found this post that details an option for use with OSX Excel, but I cannot find its analog for OSX Word. Does anybody know of a Word-equivalent to the Excel ActiveSheet.QueryTables that would work for sending POSTs in OSX?

编辑:我已经取得了一些进展.看起来您可以通过VBA调用外部程序,并且所有Mac都安装了Python,因此我编写了一个Python脚本,该脚本使用urlliburllib2将请求发送到服务器. Python文件还使用argparse从命令行解析公式字符串,字体大小和网址.

EDIT: I have made some progress. It looks like you can call external programs through VBA, and all Macs come with Python installed, so I wrote a Python script that uses urllib and urllib2 to send the request to the server. The Python file also uses argparse to parse the formula string, fontsize, and web address from the command line.

现在,我的宏可以使用类似以下内容的代码来调用我的python脚本:

Now my macro can call my python script with something like:

sCmd = "python " & pyPath & "getURL.py --formula " & Latex_Str & " --fontsize "_
    & Font_Size & " " & WebAdd
sResult = Shell(sCmd, vbNormalFocus)

用户通过应用程序输入Latex_Str的地方,Font_Size同样由用户定义的,而WebAdd是两个地址之一,具体取决于我们要生成方程式还是清除临时文件.

Where Latex_Str is input by the user through the app, Font_Size is likewise defined by the user, and WebAdd is one of two addresses, depending on whether we are generating the equation or cleaning up temporary files.

我无法弄清楚的是如何使VBA从Python脚本中读取返回值(该字符串具有服务器返回值的字符串,我需要该字符串以便以后检索图像文件). Shell命令似乎只返回一个PID编号.有人可以帮忙吗?

What I cannot figure out is how to get VBA to read the return from my Python script (a string with return values from my server that I need in order to later retrieve the image file). The Shell command only seems return a PID number. Can anybody help?

解决方案::我知道了!我能够编写一个Python脚本来处理对服务器的POST请求并打印其对stdout的响应.在社区的帮助和大量在线文档的帮助下,我随后能够使用result = vba.MacScript(command)方法从VBA使用AppleScript调用此Python脚本.这使我能够将Python脚本中的stdout读取到VBA中的字符串变量中.我的Python脚本如下:

SOLUTION: I figured it out! I was able to write a Python script to handle the POST request to the server and print its response to stdout. With the help of the community and lots of documentation online, I was then able to call this Python script using AppleScript from VBA with the result = vba.MacScript(command) method. This enabled me to read the stdout from my Python script into a string variable in VBA. My Python script was as follows:

# Import the required libraries
from urllib import urlencode
from urllib2 import Request, urlopen, URLError, ProxyHandler, build_opener, install_opener
import argparse

# Set up our argument parser
parser = argparse.ArgumentParser(description='Sends LaTeX string to web server and returns meta data used by LaTeX in Word project')
parser.add_argument('webAddr', type=str, help='Web address of LaTeX in Word server')
parser.add_argument('--formula', metavar='FRML', type=str, help='A LaTeX formula string')
parser.add_argument('--fontsize', metavar='SIZE', type=int, default=10, help='Integer representing font size (can be 10, 11, or 12. Default 10)')
parser.add_argument('--proxServ', metavar='SERV', type=str, help='Web address of proxy server, i.e. http://proxy.server.com:80')
parser.add_argument('--proxType', metavar='TYPE', type=str, default='http', help='Type of proxy server, i.e. http')

# Get the arguments from the parser
args = parser.parse_args()

# Define formula string if input
if args.formula:
    values = {'formula': str(args.fontsize) + '.' + args.formula}   # generate formula from args
else:
    values = {}

# Define proxy settings if proxy server is input.
if args.proxServ:       # set up the proxy server support
    proxySupport = ProxyHandler({args.proxType: args.proxServ})
    opener = build_opener(proxySupport)
    install_opener(opener)

# Set up the data object
data = urlencode(values)
data = data.encode('utf-8')

# Send request to the server and receive response, with error handling!
try:
    req = Request(args.webAddr, data)

    # Read the response and print to a file
    response = urlopen(req)
    print response.read()

except URLError, e:
    if hasattr(e, 'reason'):    # URL error case
        # a tuple containing error code and text error message
        print 'Error: Failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):    # HTTP error case
        # HTTP error code, see section 10 of RFC 2616 for details
        print 'Error: The server could not fulfill the request.'
        print 'Error code: ', e.code
        # print e.read()

我最近开始的与此相关的话题指出我在MacScript命令的方向上调用了我的函数并获得了字符串返回,而@CuberChase让我开始编写用于处理对服务器的调用的外部函数.非常感谢!

This related thread that I started more recently pointed me in the direction of the MacScript command for calling my function and getting a string return, and @CuberChase got me started down the path to writing an external function to handle the call to the server. Thanks a lot!

推荐答案

不幸的是,没有能力通过Mac Office从VBA直接执行 HTTP投递请求.

Unfortunately, there is no capacity to perform a HTTP Post request directly from VBA via Mac Office.

您当前正在收到错误429,指出"ActiveX组件无法创建对象",因为OS X中没有XMLHTTP对象模型(或MSXML2或WinHttp),这些对象模型仅适用于Windows.这意味着它们不适用于Word以外的任何Office程序.

You are currently getting the error 429 stating "ActiveX component can't create object" because there is no XMLHTTP object model (or MSXML2 or WinHttp) in OS X, these object models are Windows only. This means they are not available to any Office programs not just Word.

您将不得不找到一种解决方法,例如可能使用AppleScript(不确定是否可能)或在外部程序(例如curl)上发出shell命令. 此SO答案使用Curl进行HTTP Get请求,并且可能是最好的起点.

You'll have to find a work around like possibly using AppleScript (not sure if it's possible or not) or issuing a shell command on an external program such as curl. This SO answer uses Curl for an HTTP Get request and is probably the best starting place.

这篇关于在Microsoft Word 2011 for OSX中通过POST发送和接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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