如果我们想得到当前主机与远程主机是否连接,或者我们想做一个小型浏览器,我们需要使用socket写一个请求报文。废话少说,上代码。
public class Main
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Socket socket = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try
{
socket = new Socket("www.baidu.com", 80);
//post请求,请求实体放服务器需要的客户端数据,首部行后面需要一个空行,所以最后\r\n
String postString = "POST / HTTP/1.0" + "\r\n"
+ "Host:www.baidu.com:80" + "\r\n\r\n";
//get请求,请求实体为空
String getString = "GET / HTTP/1.0" + "\r\n"
+ "Host:www.baidu.com:80" + "\r\n\r\n";
//head请求,只返回报文头部,不返回请求对象
String headString="HEAD / HTTP/1.0" + "\r\n"
+ "Host:www.baidu.com:80" + "\r\n\r\n";
System.out.println("请求报文:\r\n" + getString);
outputStream = socket.getOutputStream();
outputStream.write(getString.getBytes());
outputStream.flush();
inputStream = socket.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
String readData = null;
System.out.println("响应报文:\r\n");
while ((readData = bufferedReader.readLine()) != null)
{
System.out.println(readData);
}
} catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try
{
if (outputStream != null)
outputStream.close();
if (bufferedReader != null)
bufferedReader.close();
if (inputStream != null)
inputStream.close();
if (socket != null)
socket.close();
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}