使用Golang消费第三方API的最佳实践

使用Golang消费第三方API的最佳实践 请指导我如何使用Go语言,通过用户名和密码来调用API?

这是API地址

https://emea.universal-api.pp.travelport.com/B2BGateway/connect/uAPI/AirService

需要在请求中传递以下信息

request.Headers.Add(“Authorization”, "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(“username” + “:” + “password”)));
request.ContentType = “text/xml; encoding=‘utf-8’”;
request.Method = “Post”;
request.Headers.Add(“SOAPAction”, “”);
request.Host = “travelport.com”;

我将不胜感激。


更多关于使用Golang消费第三方API的最佳实践的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

你好,

实际上,我对于如何使用 http.Get 和 http.Post 传递用户名和密码感到困惑,并且我找不到任何解决方案。

谢谢

更多关于使用Golang消费第三方API的最佳实践的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


当你尝试执行你发布的代码时会发生什么?你遇到错误了吗?如果是,可以展示给我们看看吗?

我猜你应该使用一些基本的身份验证,像这样:

client := &http.Client{}
req, err := http.NewRequest(<METHOD>, <URL>, nil)
req.SetBasicAuth(<user>, <password>)
res, err := client.Do(req)
if err != nil {
	<handle error here>
}

在Go语言中调用第三方API,特别是需要基本认证和SOAP请求的场景,可以通过以下方式实现:

package main

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "net/http"
    "strings"
)

func main() {
    // API配置
    url := "https://emea.universal-api.pp.travelport.com/B2BGateway/connect/uAPI/AirService"
    username := "your_username"
    password := "your_password"
    
    // 创建HTTP客户端
    client := &http.Client{}
    
    // 准备SOAP请求体(示例XML)
    soapBody := `<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <!-- 你的SOAP请求内容 -->
    </soap:Body>
</soap:Envelope>`
    
    // 创建请求
    req, err := http.NewRequest("POST", url, bytes.NewBufferString(soapBody))
    if err != nil {
        panic(err)
    }
    
    // 设置基本认证头
    auth := username + ":" + password
    basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
    req.Header.Add("Authorization", basicAuth)
    
    // 设置其他头信息
    req.Header.Add("Content-Type", "text/xml; charset=utf-8")
    req.Header.Add("SOAPAction", "")
    req.Host = "travelport.com"
    
    // 发送请求
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    
    // 读取响应
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("响应状态: %d\n", resp.StatusCode)
    fmt.Printf("响应内容: %s\n", string(body))
}

// 如果需要处理更复杂的SOAP请求,可以使用专门的SOAP客户端库
import (
    "github.com/hooklift/gowsdl/soap"
)

type AirService struct {
    client *soap.Client
}

func NewAirService(username, password string) *AirService {
    // 创建带认证的SOAP客户端
    client := soap.NewClient(
        "https://emea.universal-api.pp.travelport.com/B2BGateway/connect/uAPI/AirService",
        soap.WithBasicAuth(username, password),
    )
    
    return &AirService{client: client}
}

对于需要重试和错误处理的场景:

func callAPIWithRetry(url, username, password, soapBody string) ([]byte, error) {
    maxRetries := 3
    var lastErr error
    
    for i := 0; i < maxRetries; i++ {
        resp, err := makeRequest(url, username, password, soapBody)
        if err == nil {
            return resp, nil
        }
        
        lastErr = err
        // 可以添加指数退避等待
    }
    
    return nil, fmt.Errorf("API调用失败,重试%d次后仍然错误: %v", maxRetries, lastErr)
}

func makeRequest(url, username, password, soapBody string) ([]byte, error) {
    req, err := http.NewRequest("POST", url, bytes.NewBufferString(soapBody))
    if err != nil {
        return nil, err
    }
    
    auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
    req.Header.Set("Authorization", "Basic "+auth)
    req.Header.Set("Content-Type", "text/xml; charset=utf-8")
    req.Header.Set("SOAPAction", "")
    req.Host = "travelport.com"
    
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    
    if resp.StatusCode >= 400 {
        return nil, fmt.Errorf("API返回错误状态码: %d", resp.StatusCode)
    }
    
    return ioutil.ReadAll(resp.Body)
}
回到顶部