如何在Go(golang)中进行身份验证并通过HTTP发送XML SOAP请求

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

How do I get to authenticate and send xml through http in Go (golang) SOAP

问题

我正在尝试通过http(SOAP)连接到服务器。

但是我遇到了一个错误:401 - 未经授权:由于凭据无效而拒绝访问

那么,在发送请求之前,我该如何发送凭据?我已经做到了这一点。

package main

import (
  "net/http"
  "bytes"
  "fmt"
  "io/ioutil"
)

func main() {

  buf := []byte(`<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ClientGetByGuid xmlns="http://tempuri.org/">
      <guid>fc40a874-2902-4539-b8e7-6aa7084644ec</guid>
    </ClientGetByGuid>
  </soap:Body>
</soap:Envelope>`)
  body := bytes.NewBuffer(buf)
  r, _ := http.Post("http://mywebsite.com.br/service.svc?wsdl", "text/xml", body)

  response, _ := ioutil.ReadAll(r.Body)
  fmt.Println(string(response))
}

谢谢。

英文:

I'm trying to connect to a server through http (SOAP).

But I'm getting an error: 401 - Unauthorized: Access is denied due to invalid credentials.

So, how can I send the credentials before the request? I've got here so far.

package main

import (
  &quot;net/http&quot;
  &quot;bytes&quot;
  &quot;fmt&quot;
  &quot;io/ioutil&quot;
)

func main() {

  buf := []byte(`&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;soap:Envelope xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; xmlns:soap=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;
  &lt;soap:Body&gt;
    &lt;ClientGetByGuid xmlns=&quot;http://tempuri.org/&quot;&gt;
      &lt;guid&gt;fc40a874-2902-4539-b8e7-6aa7084644ec&lt;/guid&gt;
    &lt;/ClientGetByGuid&gt;
  &lt;/soap:Body&gt;
&lt;/soap:Envelope&gt;`)
  body := bytes.NewBuffer(buf)
  r, _ := http.Post(&quot;http://mywebsite.com.br/service.svc?wsdl&quot;, &quot;text/xml&quot;, body)

  response, _ := ioutil.ReadAll(r.Body)
  fmt.Println(string(response))
}

Thanks.

答案1

得分: 4

如果你在谈论HTTP基本身份验证,创建一个Request对象并使用SetBasicAuth(username, password string)方法。

更多信息请参见这个问题

英文:

If you are talking about HTTP Basic Auth, create a Request object and use the SetBasicAuth(username, password string) method.

See this question for more information.

huangapple
  • 本文由 发表于 2013年6月24日 22:41:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/17278253.html
匿名

发表评论

匿名网友

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

确定