GET request with Java sockets

别说谁变了你拦得住时间么 提交于 2019-12-04 08:17:34
RAJKUMAR NAGARETHINAM

if the about page link is about.html ,then you have change this line wtr.println("GET / HTTP/1.1") into wtr.println("GET /about.html HTTP/1.1").

in socket creation remove the /about

wtr.println("GET / HTTP/1.1");--->this line call the home page of the host you specified.

you need open Socket to url without path e.g.

Socket("www.badunetworks.com", port);

and after send command GET /{path} HTTP/1.1 e.g.

GET /about HTTP/1.1

... other header...

When you're doing such a low-level access to a webserver, you should understand the 7 OSI layers. Socket is on layer 5 and HTTP on layer 7. That's also the reason, why java.net.Socket only accepts host names or InetAddr and no URLs. To do it with sockets, you have to implement the HTTP protocol properly, that is

  • Create a socket connection to the host and port, i.e. www.badunetworks.com and 80
  • Send a HTTP packet to the outputstream containing, method, resource by path and protocol version, i.e. GET /about/ HTTP/1.1
  • Read and interpret the response properly (headers and body)

But I wonder why you're doing it this complicated, there are a lot of alternatives to implementing low-level http clients yourself:

  • good old java.net.URL, as deprecated as its handling is, it's still one of the easiest way to read a resource, just call openStream() to read it
  • Apache HTTP Client is one of the most widely used http client implementation for java, which is quite easy to use and more flexible than the reading via URL
  • javax.ws.rs has a good builder api for creating web clients
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!