少说话多写代码之GO开发——003:go访问webservice

栏目: Go · 发布时间: 7年前

内容简介:以post请求为例,post方式,go访问webservice很简单,使用http.Post方法。参数则写起来比较麻烦,使用xml拼接方式。

以post请求为例,

post方式,go访问webservice很简单,使用http.Post方法。

参数则写起来比较麻烦,使用xml拼接方式。

我们来看在postman中如何访问的: https://blog.csdn.net/yysyangyangyangshan/article/details/86650012 ,这里需要把参数拼接成xml格式。

看代码如何实现,

package main
import (
	"fmt"
    "net/http"
	"io/ioutil"
	"bytes"
	"unsafe"
)

func checkErr(err error){
	if err!=nil{
		panic(err)
	}
}
func main(){
	//测试调用webservice
	paras :="<paraName1>hhhh</paraName1 >"+
	"<paraName2>kkkk</paraName2>"+
	"<paraName3>TY</paraName3>"+
	"<paraName4>1</paraName4>"

	postStr := GenSOAPXml("http://tempuri.org/", "MethodName", paras)
	PostWebService("http://ganmane.com/hehe/wodishen.asmx", "MethodName", postStr)
}

func PostWebService(url string, method string, value string) string {
	res, err := http.Post(url, "text/xml; charset=utf-8", bytes.NewBuffer([]byte(value)))
	//错误日志
	if err != nil {
		fmt.Println("post error", err)
	}
	data, err := ioutil.ReadAll(res.Body)
	
	if err != nil {
		fmt.Println("read error", err)
	}
	res.Body.Close()
	fmt.Printf("result----%s", data)
	str :=(*string)(unsafe.Pointer(&data))
	return  *str
}

func GenSOAPXml(nameSpace string, methodName string, valueStr string) string {
	soapBody := `<?xml version="1.0" encoding="utf-16"?>`
	soapBody += `<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">`
	soapBody += " <soap:Body>"
	soapBody += "<" + methodName + " xmlns=\"" + nameSpace + "\">"
	//以下是具体参数
	soapBody +=  valueStr 

	soapBody += "</" + methodName + "> </soap:Body></soap:Envelope>"
	fmt.Println(soapBody)
	return soapBody
}

代码中对应地方改为实际的参数和地址方法即可。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Algorithmic Beauty of Plants

The Algorithmic Beauty of Plants

Przemyslaw Prusinkiewicz、Aristid Lindenmayer / Springer / 1996-4-18 / USD 99.00

Now available in an affordable softcover edition, this classic in Springer's acclaimed Virtual Laboratory series is the first comprehensive account of the computer simulation of plant development. 150......一起来看看 《The Algorithmic Beauty of Plants》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具