go 几种网络请求举例

要用到net/http库

提供这几种,post、get、postform请求,复杂的用一下client请求。

具体看代码吧

// nethttp project main.go
package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

func main() {
	fmt.Println("Hello World!")

	//testGet("http://my.oschina.net/lockupme/blog/698500")

	//testClient("http://my.oschina.net/lockupme/blog/698500")

	testPost("http://h5.test.com/t.php", "{\"username\":\"lock\",\"password\":\"123456\"}")

	//testPostImage("http://h5.test.com/t.php")
}

func testPostImage(url string) {
	file, _ := os.Open("3.png")

	defer file.Close()
	bufr := bufio.NewReader(file)

	resp, err := http.Post(url, "application/x-www-form-urlencoded", bufr)
	if err != nil {
		fmt.Println("error")
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))

}

func testPost(url, postvalue string) {
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postvalue))
	if err != nil {
		fmt.Println("error")
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

//get request
func testGet(url string) {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("error")
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

//http.Client和http.NewRequest来模拟请求
func testClient(url string) {
	client := &http.Client{}

	reqest, _ := http.NewRequest("GET", url, nil)

	reqest.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	reqest.Header.Set("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3")
	//reqest.Header.Set("Accept-Encoding", "gzip,deflate,sdch")
	reqest.Header.Set("Accept-Language", "zh-CN,zh;q=0.8")
	reqest.Header.Set("Cache-Control", "max-age=0")
	reqest.Header.Set("Connection", "keep-alive")

	response, _ := client.Do(reqest)
	if response.StatusCode == 200 {
		body, _ := ioutil.ReadAll(response.Body)
		fmt.Println(string(body))
	}
}

服务器用php做测试的,以流形式接受:

$streamData = file_get_contents('php://input') ? file_get_contents ('php://input') : gzuncompress ($GLOBALS['HTTP_RAW_POST_DATA']);

print_r(json_decode($streamData, true));

//echo file_put_contents("3.png", $streamData, true);
exit;

 

转载于:https://my.oschina.net/lockupme/blog/699424

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值