微信

使用微信服务,更方便

职友集>Java面试题 > 用java socket向http服务器发送get命令

用java socket向http服务器发送get命令

2015-06-05 06:30:01 阅读( 328 )

2448人 收藏本页

标签:Java面试题

代码如下

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class HttpConnection
{

/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException
{
String ip = “127.0.0.1″ ;
int port = 80 ;

Socket soc = new Socket(ip, port);

System.out.println(“———————————-”);
System.out.println(“\n\n\n\n”);

BufferedReader in = new BufferedReader( new InputStreamReader(soc.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));

StringBuffer meth = new StringBuffer();
meth.append(“GET / HTTP/1.1\r\n”);
// meth.append(“accept:*/*\r\n”);
meth.append(“host:127.0.0.1\r\n”);
meth.append(“”);
meth.append(“”);

out.write(meth.toString());
out.write(“\r\n”);
out.flush();

String line = null ;

while( (line = in.readLine())!= null)
{
System.out.println(line);
}

}

}

输出
———————————-

HTTP/1.1 200 OK
Date: Tue, 06 Mar 2012 12:32:58 GMT
Server: Apache/2.2.22 (Win32)
Last-Modified: Tue, 06 Mar 2012 11:46:06 GMT
ETag: “b000000008d9e-57-4ba9196947acd”
Accept-Ranges: bytes
Content-Length: 87
Content-Type: text/html




Here is body!



终于看到了期待已久的HTTP/1.1 200 OK 。

来自IT公司面试手册

下一篇:我的Java面试总结

上一篇:诡异的Java笔试面试题

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题