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();
        }
    }
  • 相关阅读:
    Thinkphp5 对接百度云对象存储 BOS (上传、删除)
    php 删除富文本编辑器保存内容中的其他代码(保留中文)
    ffmreg thinkphp 控制器 获取音频视频详细信息(获取时长)
    selenium+testng+java+poi进行excel的数据参数化
    linux中磁盘配额管理
    linux中挂载和卸载文件系统
    linux中vi编辑器的练习
    Linux基础命令
    Nginx流量复制
    Python脚本
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7807747.html
Copyright © 2011-2022 走看看