Java发送HTTP请求

用Java发送HTTP请求,就是用Java代码代替浏览器的作用。

首先你需要创建一个Socket对象,与IP为127.0.0.1,端口为80的服务器绑定;

然后获取Socket对象的输出流对象,向服务器发送请求信息;

最后再获取Socket对象的输入流对象,接收服务器的响应信息;

 

public static void main(String[] args) throws UnknownHostException, IOException {
		Socket s = new Socket("127.0.0.1", 80);
		Writer out = new OutputStreamWriter(s.getOutputStream());
		String str = getMsg();
//		String str = postMsg();
		out.write(str);
		out.flush();
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String line = null;
		while((line = reader.readLine()) != null) {
			System.out.println(line);
		}
	}
	
	public static String getMsg() {
		////"GET /hello/index.jsp HTTP/1.1\r\nhost:127.0.0.1:8080\r\n\r\n"
		StringBuilder sb = new StringBuilder();
		sb.append("GET /hello/index.jsp HTTP/1.1").append("\r\n");
		sb.append("host:127.0.0.1:8080").append("\r\n\r\n");
		return sb.toString();
	}
	
	public static String postMsg() {
		StringBuilder sb = new StringBuilder();
		sb.append("POST /hello/index.jsp HTTP/1.1").append("\r\n");
		sb.append("Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*").append("\r\n");
		sb.append("Referer: http://localhost/hello/index.jsp").append("\r\n");
		sb.append("Accept-Language: zh-cn,en-US;q=0.5").append("\r\n");
		sb.append("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)").append("\r\n");
		sb.append("Content-Type: application/x-www-form-urlencoded").append("\r\n");
		sb.append("Accept-Encoding: gzip, deflate").append("\r\n");
		sb.append("Host: localhost:80").append("\r\n");
		sb.append("Content-Length: 36").append("\r\n");
		sb.append("Connection: Keep-Alive").append("\r\n");
		sb.append("Cache-Control: no-cache").append("\r\n");
		sb.append("\r\n");
		sb.append("username=hello");
		return sb.toString();
	}

 

<!--EndFragment-->

相关推荐