• 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();
        }
    }
  • 相关阅读:
    ReaHat7.6/7.7 最小化安装更新yum源
    Navicat Premium For Mac 12.0.2x 破解教程
    java程序员经常使用的Intellij Idea插件
    NDK版本 下载地址
    在Intellij IDEA下用X-debug调试PHP
    DMSFrame 之查询表达式用法(一)
    Wise 打包细节
    将Centos的yum源更换为国内的阿里云(163)源
    Centos下安装 .net Core运行程序
    使用 Docker 一步搞定 ZooKeeper 集群的搭建
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7807747.html
Copyright © 2020-2023  润新知