zoukankan      html  css  js  c++  java
  • Httpclient入门代码

    /**
     * Project Name:httpClient
     * File Name:Test.java
     * Package Name:httpClient
     * Date:2017年11月9日上午8:32:00
     * Copyright (c) 2017, 2692613726@qq.com All Rights Reserved.
     *
    */
    
    package httpClient;
    
    import java.io.IOException;
    
    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    /**
     * ClassName:Test 
     * Function: TODO ADD FUNCTION. 
     * Reason:     TODO ADD REASON. 
     * Date:     2017年11月9日 上午8:32:00 
     * @author   michael
     * @version  
     * @since    JDK 1.7
     * @see      
     */
    public class Test {
        public static void main(String[] args) throws Exception, IOException {
            CloseableHttpClient client = HttpClients.createDefault();
            //请求起始行
            HttpGet get= new HttpGet("http://www.sina.com.cn/");
            //请求首部--可选的,User-Agent对于一些服务器必选,不加可能不会返回正确结果  
            get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");  
            //执行请求
            CloseableHttpResponse response = client.execute(get);
            
            
            //获得起始行
            System.out.println(response.getStatusLine().toString()+"
    ");
            //获取首部
            Header[] hs =  response.getAllHeaders();
            for (Header header : hs) {
                System.out.println(header.getName()+"	"+header.getValue()+"
    ");
            }
            //获取实体
            HttpEntity entity = response.getEntity();
            System.out.println(EntityUtils.toString(entity,"utf-8"));
            EntityUtils.consume(entity);//释放实体
            response.close();
            client.close();
        }
    }
  • 相关阅读:
    计算机中的进制和编码
    操作系统简史
    电脑结构和CPU、内存、硬盘三者之间的关系
    电脑简史
    使用开源my-deploy工具实现开发环境的代码自动化部署
    使用Let’s Encrypt创建nginx免费SSL证书
    VM ESXI 服务器虚拟化资料积累
    python mysql连接函数
    python日期格式转换小记
    Python模块学习
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7807747.html
Copyright © 2011-2022 走看看