在Go语言中通过TCP连接进行HTTP请求。

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

Making http request by tcp connection in go

问题

package main

import (
	"crypto/tls"
	"fmt"
)

func main() {
	conf := &tls.Config{}
	conn, _ := tls.Dial("tcp", "www.google.com:443", conf)
	data := []byte("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n")
	conn.Write(data)
	buf := make([]byte, 5000)
	conn.Read(buf)
	fmt.Println(string(buf[:]))
}

我正在尝试通过原始的TCP连接数据进行HTTP请求,但是收到了400 Bad Request的错误响应,请问问题出在哪里?

英文:
package main

import (
	"crypto/tls"
	"fmt"
)

func main() {
	conf := &tls.Config{}
	conn, _ := tls.Dial("tcp", "www.google.com:443", conf)
	data := []byte("GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n")
	conn.Write(data)
	buf := make([]byte, 5000)
	conn.Read(buf)
	fmt.Println(string(buf[:]))
}

I am trying to make http request by raw tcp connection data, but get an error response of 400 Bad Request, what's the issue.

答案1

得分: 2

数据中有一个拼写错误。

HTTP1.1 应该是 HTTP/1.1


我想分享一下我是如何发现这个错误的,希望能帮助到其他人。

当我想解决一个我不太熟悉的问题时,我首先要做的是找出它在正常情况下是什么样子的。我之前使用过 nc,所以我首先尝试使用它。

这是 nc 的 man 页面上的一个示例:

$ printf "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80

所以我首先将 host.example.com 替换为 www.google.com

$ printf "GET / HTTP/1.0\r\n\r\n" | nc www.google.com 80

它正常工作!

然后将 HTTP/1.0 替换为 HTTP/1.1。仍然正常工作!

然后添加 Host 头部:

$ printf "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n" | nc www.google.com 80

正常工作!

然后复制问题中的字符串:

$ printf "GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n" | nc www.google.com 80

这次得到了 400 Bad Request

这是一个很大的进步!请求中有些问题。通过比较这两个请求,很容易发现拼写错误。

最后,在原始演示中修复这个错误,并运行演示以验证问题是否已解决。完成!

谢谢阅读!

英文:

There is a typo in the data.

HTTP1.1 should be HTTP/1.1.


I would like to share how I found the typo in the hope that it helps others.

When I want to address an issue that I'm not so familiar with, the first thing I do is to find out what it looks like when it works. I have used nc before, so I will try it first.

This is an example from the man page of nc:

$ printf "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80

So I replaced host.example.com with www.google.com first:

$ printf "GET / HTTP/1.0\r\n\r\n" | nc www.google.com 80

It works!

Then replace HTTP/1.0 with HTTP/1.1. Still works!

Then add the Host header:

$ printf "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n" | nc www.google.com 80

Works!

Then copy the string from the question:

$ printf "GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n" | nc www.google.com 80

Got 400 Bad Request this time.

This is a big step forward! There is something wrong in the request. It's easy to spot the typo by comparing the two requests.

Finally, fix the typo in the original demo, and run the demo to verify that the issue has been addressed. Done!

Thanks for reading!

huangapple
  • 本文由 发表于 2023年4月6日 11:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75945605.html
匿名

发表评论

匿名网友

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

确定