解决的问题是 go发送多维数组的form格式的post请求
前提:只能是form格式,json是没有这个问题的
就是发送如下php格式application/x-www-form-urlencoded的post请求
$form_params=array (
'r_list' =>
array (
0 =>
array (
'r_address' => 'r_address',
'r_city' => 'r_city',
'r_district' => 'r_district',
'r_mobile' => 'r_mobile',
'r_name' => '收货人',
'r_province' => 'r_province',
'shop_order' => 'shop_order',
),
1 =>
array (
'r_address' => 'r_address2',
'r_city' => 'r_city2',
'r_district' => 'r_district2',
'r_mobile' => 'r_mobile2',
'r_name' => '收货人1',
'r_province' => 'r_province2',
'shop_order' => 'shop_order2',
),
),
'send_address' => 'send_address',
'send_city' => 'send_city',
'send_district' => 'send_district',
'send_mobile' => 'send_mobile',
'send_name' => 'send_name',
'send_province' => 'send_province',
'username' => 'nanyounan',
)
$client = new Client();
$request = new Request('POST', 'xxxxxxx', [
'form_params' => $form_params
]);
问题:go怎么写这样多维数组的请求
细分为下面的几个问题
- go和php的接收差异
go在请求时吧map[key][]value 转成了key=value1&key=value2,而不是key[0]=value1&key[1]=value2,这样php在接收时只能接受到一个value - go的form格式的post请求限制
go在把form格式的post请求进行转码的时候,很多都是只解析表层,例如: 如果遇到一维数组的话,他是解析成key=value1&key=value2 如果遇到二维数组的话,他解析失败,因为解析键值对(key=value)的时候,默认的值(value)是字符串,不是数组.但是二维数组键值对的值是一个数组(map类型),go就会解析失败
重点来了.解决思路:自己手写解析后的字符串,让go直接传递解析后的form格式的post请求
ploady:=make(url.Values)
ploady.Set("send_name",sendName)
ploady.Set("send_mobile",sendMobile)
ploady.Set("send_province",sendProvince)
ploady.Set("send_province",sendProvince)
ploady.Set("send_city",sendCity)
ploady.Set("send_district",sendDistrict)
ploady.Set("send_address",sendAddress)
for i, n := 0, len(rList); i < n; i++ {
for key, v := range rList[i] {
valueToString := v.(string)
ploady.Set(fmt.Sprintf("%s%d%s%s%s","r_list[",i,"][",key,"]"),valueToString)
}
}
res := newHttpPostForm("/api/buyOrders", ploady)
func newHttpPostForm(postUrl string, payload url.Values) map[string]interface{}{
fmt.Println(payload)
resp, _ := http.PostForm("http://127.0.0.1:8080/open/app",payload)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
var res map[string]interface{}
_ = json.Unmarshal(body, &res)
return res
}
后记
如果以上方式不适用的话,可以通过php的http_build_query方法获取post请求值的转码,然后通过go的url.QueryUnescape方法获取到具体的格式,然后自己编写字符串
|