zoukankan      html  css  js  c++  java
  • go请求第三方接口,使用go原生的方法去请求

    import (
       "io/ioutil"
       "log"
       "net/http"
    )

    get请求:

    resp, err := http.Get("http://localhost:6002/baiduTrans")
       if err != nil {
          log.Fatalln(err)
       }
    //We Read the response body on the line below.
       body, err := ioutil.ReadAll(resp.Body)
       if err != nil {
          log.Fatalln(err)
       }
    //Convert the body to type string
       sb := string(body)
       log.Printf(sb)

    这种请求方式的缺点是使用query传参,如果参数中包含了空格等等其他字符,他不会自动像我们浏览器的url地址一样,自动将特殊字符转义为能够识别的,导致接口无法请求成功。

    post请求:

    import (
       "bytes"
       "encoding/json"
       "io/ioutil"
       "log"
       "net/http"
    )
    
    func main() {
    //Encode the data
       postBody, _ := json.Marshal(map[string]string{
          "name":  "Toby",
          "email": "Toby@example.com",
       })
       responseBody := bytes.NewBuffer(postBody)
    //Leverage Go's HTTP Post function to make request
       resp, err := http.Post("https://postman-echo.com/post", "application/json", responseBody)
    //Handle Error
       if err != nil {
          log.Fatalf("An Error Occured %v", err)
       }
       defer resp.Body.Close()
    //Read the response body
       body, err := ioutil.ReadAll(resp.Body)
       if err != nil {
          log.Fatalln(err)
       }
       sb := string(body)
       log.Printf(sb)
    }

    来自于:https://blog.logrocket.com/making-http-requests-in-go/

  • 相关阅读:
    返回数组指针的函数形式
    zoj 2676 网络流+01分数规划
    2013 南京理工大学邀请赛B题
    poj 2553 强连通分支与缩点
    poj 2186 强连通分支 和 spfa
    poj 3352 边连通分量
    poj 3177 边连通分量
    poj 2942 点的双连通分量
    poj 2492 并查集
    poj 1523 求割点
  • 原文地址:https://www.cnblogs.com/lxz123/p/15217807.html
Copyright © 2011-2022 走看看