HTTP客户端

import java.net.URL;
import java.net.URLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.net.HttpURLConnection;

/**
客户端仅仅是获取服务端的信息
*/
public class HttpClient{
    private String urlString;
    public static void main(String[] args) throws Exception{
        if(args.length!=1){
            System.out.println("控制台参数错误!");
            //终止当前运行的Java虚拟机。
            System.exit(1);
            }
        HttpClient client = new HttpClient(args[0]);
        client.run();
        }
    
    public HttpClient(String url){
        this.urlString = url;
        }
        
    private void run() throws Exception{
        URL url = new URL(this.urlString);
        URLConnection conn = url.openConnection();
        if(conn instanceof HttpURLConnection){
            HttpURLConnection httpConn = (HttpURLConnection)conn;
            String key;
            String value;
            System.out.println("The Headers");
            System.out.println("=========================================");
            for(int i=1;;i++){
                if((key=httpConn.getHeaderFieldKey(i))==null){
                    break;
                    }
                if((value=httpConn.getHeaderField(i))==null){
                    break;
                    }
                System.out.println("key["+key+"]");
                System.out.println("value["+value+"]");    
                }
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String line;
            System.out.println("Content");
            System.out.println("=========================================");
            while((line=reader.readLine())!=null){
                System.out.println(line);
                }
            }
    }
}    

执行结果:
G:maul keyboard
etwork programming>java HttpClient http://www.google.cn
The Headers
=========================================
key[Accept-Ranges]
value[none]
key[Vary]
value[Accept-Encoding]
key[Content-Type]
value[text/html]
key[Date]
value[Sat, 10 Nov 2018 10:56:42 GMT]
key[Expires]
value[Sat, 10 Nov 2018 10:56:42 GMT]
key[Cache-Control]
value[private, max-age=0]
key[Last-Modified]
value[Thu, 08 Dec 2016 01:00:57 GMT]
key[X-Content-Type-Options]
value[nosniff]
key[Server]
value[sffe]
key[X-XSS-Protection]
value[1; mode=block]
key[Transfer-Encoding]
value[chunked]
Content
=========================================
<!DOCTYPE html>
<html lang="zh">
  <meta charset="utf-8">
  <title>Google</title>
  <style>
    html { background: #fff; margin: 0 1em; }
    body { font: .8125em/1.5 arial, sans-serif; text-align: center; }
    h1 { font-size: 1.5em; font-weight: normal; margin: 1em 0 0; }
    p#footer { color: #767676; font-size: .77em; }
    p#footer a { background: url(//www.google.cn/intl/zh-CN_cn/images/cn_icp.gif) top right no-repeat; padding: 5px 20px 5px 0; }
...
原文地址:https://www.cnblogs.com/celine/p/9940270.html