GO语言: GET请求和Post请求,body传参

package main

import (

"bytes"

"encoding/json"

"fmt"

"io/ioutil"

"log"

"net/http"

)

func main() {

//生成client 参数为默认

  fmt.Println("--------------------GET-------------------")

url :="http://localhost:8888/user/getUserInfo"

  map0 :=make(map[string]interface{})

map0["id"] =1

  str0,_ :=json.Marshal(map0)

s0,_ :=DoBytesHTTP(url,"GET",str0)

fmt.Println(string(s0))

fmt.Println("------------------POST---------------------")

urlPost :="http://localhost:8888/user/getUserList"

  map1 :=make(map[string]interface{})

map1["page"] =1

  map1["pageSize"] =1

  str1,_ :=json.Marshal(map1)

s1,_ :=DoBytesHTTP(urlPost,"POST",str1)

fmt.Println(string(s1))

}

func DoBytesHTTP(url,typeHttp string,data []byte) ([]byte,error) {

body :=bytes.NewReader(data)

request,err :=http.NewRequest(typeHttp,url,body)

request.Header.Set("Content-Type","application/json;charset=utf-8")

request.Header.Add("x-token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVVUlEIjoiZGRjYmFkZjEtNWJhOS00MWRlLTg0OWEtMWUxZjg1NjU5ZjUxIiwiSUQiOjEsIlVzZXJuYW1lIjoiYWRtaW4xMjMiLCJOaWNrTmFtZSI6ImNkanZoZmh2ZnYiLCJBdXRob3JpdHlJZCI6Ijg4OCIsIkJ1ZmZlclRpbWUiOjg2NDAwLCJleHAiOjE2MzczNzA1NDQsImlzcyI6InFtUGx1cyIsIm5iZiI6MTYzNjc2NDc0NH0.TKoc-1tEJJjjc4nZQ5hi5cXMIWJF1BC1I2du1NT-08E")

if err !=nil {

log.Println("http.NewRequest,[err=%s][url=%s]",err,url)

return []byte(""),err

  }

request.Header.Set("Connection","Keep-Alive")

var resp *http.Response

  resp,err =http.DefaultClient.Do(request)

if err !=nil {

log.Println("http.Do failed,[err=%s][url=%s]",err,url)

return []byte(""),err

  }

defer resp.Body.Close()

b,err :=ioutil.ReadAll(resp.Body)

if err !=nil {

log.Println("http.Do failed,[err=%s][url=%s]",err,url)

}

return b,err

}

你可能感兴趣的:(GO语言: GET请求和Post请求,body传参)