Example
/**
* we reuse a class written in example:
* http://stackoverflow.com/documentation/sockets/2876/introduction-to-sockets#t=201607262114505531351
* pleas to familiar with it first to continue with this one
**/
public class WriteToSocketExample extends ConnectSocketExample {
private String CRLF = "\r\n"; // line termination (separator)
/**
* write a simple http get request to socket
* @param host - host to establish a connection
* (http server - see ConnectSocketExample HTTP_PORT )
* @param path - path to file ( in this case a url location - part used in browser after host)
* @return a connected socket with filled in raw get request
* @throws IOException - see ConnectSocketExample.connectSocket(host);
*/
protected Socket writeGetToSocket(String host, String path) throws IOException {
// create simple http raw get request for host/path
String rawHttpGetRequest = "GET "+ path +" HTTP/1.1 " + CRLF // request line
+ "Host: "+ host + CRLF
+ CRLF;
// get bytes of this request using proper encodings
byte[] bytesOfRequest = rawHttpGetRequest.getBytes(Charset.forName("UTF-8)"));
// create & connect to socket
Socket socket = connectSocket(host);
// get socket output stream
OutputStream outputStream = socket.getOutputStream();
// write to the stream a get request we created
outputStream.write(bytesOfRequest);
// return socket with written get request
return socket;
}
/**
* create, connect and write to socket simple http get request
* then dump response of this request
* @throws IOException
*/
public void writeToSocketAndDumpResponse() throws IOException {
// send request to http server for / page content
Socket socket = writeGetToSocket("google.com", "/");
// now we will read response from server
InputStream inputStream = socket.getInputStream();
// create a byte array buffer to read respons in chunks
byte[] buffer = new byte[1024];
// define a var to hold count of read bytes from stream
int weRead;
// read bytes from sockets till exhausted or read time out will occurred ( as we didn't add in raw get header Connection: close (default keep-alive)
while ((weRead = inputStream.read(buffer)) != -1) {
// print what we have read
System.out.print(new String(buffer));
}
}
}