如何在应用程序中进行GET请求

huangapple go评论149阅读模式
英文:

How to make a get request mid application

问题

在GAE中,要在应用程序中创建一个GET HTTP请求,你可以使用Python的urlfetch模块。以下是一个示例代码,展示了如何发送GET请求并获取响应体:

from google.appengine.api import urlfetch

def make_get_request(url):
    result = urlfetch.fetch(url)
    if result.status_code == 200:
        response_body = result.content
        return response_body
    else:
        return None

# 调用函数并传入URL
response = make_get_request("http://example.com")
if response:
    print(response)
else:
    print("请求失败")

在上面的示例中,make_get_request函数接受一个URL参数,并使用urlfetch.fetch方法发送GET请求。如果响应的状态码为200,表示请求成功,可以通过result.content获取响应体。如果请求失败或响应状态码不是200,函数将返回None

请注意,urlfetch模块是GAE特定的模块,用于在应用程序中进行HTTP请求。

英文:

How would I go about creating a GET HTTP request mid application in GAE? I don't want to have it as a handler function, I simply have a URL that I need to get the response body from.

答案1

得分: 1

使用urlfetch包。

ctx := appengine.NewContext(r)   // r是处理程序的*http.Request参数
client := urlfetch.Client(ctx)  
resp, err := client.Get("http://example.com")
if err != nil {
    // 处理错误
}
body := resp.Body // body是包含响应正文的io.Reader

这里有一个完整的示例

英文:

Use the urlfetch package.

ctx := appengine.NewContext(r)   // r is the *http.Request arg to the handler
client := urlfetch.Client(ctx)  
resp, err := client.Get("http://example.com")
if err != nil {
    // handle the error 
}
body := resp.Body // body is an io.Reader containing the response body

Here's a complete example.

答案2

得分: 0

我还没有使用过它,如果这个方法不起作用,我很抱歉。根据GAE的文档,你可能想要使用urlfetch来获取一个*http.Client,代码如下(注意:context包是Go 1.7中的标准包):

import (
    "context" // Go 1.7
    // "golang.org/x/net/context" // Go < 1.7
    "google.golang.org/appengine/urlfetch"
)

client := urlfetch.Client(context.Background())
resp, err := client.Get("http://example.com/")
英文:

I haven't used it so apologies if this doesn't work. According to GAE's docs you probably want to use urlfetch to get a *http.Client something like (N.B. the context package is standard in the just released Go 1.7):

import (
    &quot;context&quot; // Go 1.7
    // &quot;golang.org/x/net/context&quot; // Go &lt; 1.7
    &quot;google.golang.org/appengine/urlfetch&quot;
)

client := urlfetch.Client(context.Background())
resp, err := client.Get(&quot;http://example.com/&quot;)

huangapple
  • 本文由 发表于 2016年8月19日 07:07:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/39028806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定