2018-05-20 apache-httpclient

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>test</scope>
        </dependency>
package com.guoyasoft.autoAPI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ApacheHttp {
    /*
     * 请求步骤 使用帮助类HttpClients创建CloseableHttpClient对象.
     * 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例. 使用addHeader方法添加请求头部,诸如User-Agent,
     * Accept-Encoding等参数. 可调用HttpGet、HttpPost共同的setParams(HetpParams
     * params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity
     * entity)方法来设置请求参数。 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
     * 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等. 释放连接。无论执行方法是否成功,都必须释放连接
     * 
     * 作者:AnakinSky 链接:https://www.jianshu.com/p/99c627c6aa9b 來源:简书
     * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
     */

    @Test
    public static void httpPost() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            String url = "http://47.98.226.232:8080/guoya-medium/user/login.action";
            HttpPost httpPost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);

            httpPost.addHeader("Host", "47.98.226.232:8080");
            httpPost.addHeader("Connection", "keep-alive");

            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("userName", "guoya"));
            paramList.add(new BasicNameValuePair("password",
                    "46da9da65fae31c690e7c391f37b085a"));
            paramList.add(new BasicNameValuePair("checkCode", "12345"));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            httpResponse = httpClient.execute(httpPost);

            reader = new BufferedReader(new InputStreamReader(httpResponse
                    .getEntity().getContent(), "UTF-8"));

            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }

        } catch (Exception var) {
            var.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
            httpClient.close();
        }
        System.out.println(response.toString());
        boolean isSuccess = response.toString().contains("班级类型");
        Assert.assertEquals(true, isSuccess);
        // return response.toString();

    }

    @Test
    public static void httpsPost() throws Exception {
        

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            String url = "http://47.98.226.232:8080/guoya-medium/user/login.action";
            HttpPost httpPost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);

            httpPost.addHeader("Host", "47.98.226.232:8080");
            httpPost.addHeader("Connection", "keep-alive");

            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("userName", "guoya"));
            paramList.add(new BasicNameValuePair("password",
                    "46da9da65fae31c690e7c391f37b085a"));
            paramList.add(new BasicNameValuePair("checkCode", "12345"));

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            httpResponse = httpClient.execute(httpPost);

            reader = new BufferedReader(new InputStreamReader(httpResponse
                    .getEntity().getContent(), "UTF-8"));

            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }

        } catch (Exception var) {
            var.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (httpResponse != null) {
                httpResponse.close();
            }
            httpClient.close();
        }
        System.out.println(response.toString());
        boolean isSuccess = response.toString().contains("班级类型");
        Assert.assertEquals(true, isSuccess);
        // return response.toString();
        
    }

    public void httpGet() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet("http://www.baidu.com/");
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: "
                            + entity.getContentLength());
                    // 打印响应内容
                    System.out.println("Response content: "
                            + EntityUtils.toString(entity));
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容

  • 昨天发生的糟心是太让我心情郁闷了,但是我不想把事情写出来,我这个人好像不是那么爱诉说的人,可能觉得我说了反而更加难...
    LilyM_海蕾阅读 94评论 0 1
  • 1 今天运动,空跳,加上脖颈操。这段时间只能先考虑省课题申报。没有阅读时间。今天还没听书。 上课五节,完成玩转语文...
    躲进小楼看灯火阅读 193评论 0 0
  • 每个人都在不停的寻找自己的位置和方向,或前或后或左或右 7岁时 有人和小伙伴在欢声笑语 有人与颜真卿欧阳询在...
    绾之微木阅读 183评论 0 0
  • 文章看多了,应该欣赏一些美,心情会更美丽,这是我收集的一些童真,希望朋友们能像她们的笑容一样,在快节奏的生活中像她...
    闫腾影像阅读 232评论 0 0
  • 记忆中,我生活所在的地方,几乎没有以养蚕为生的人。养蚕人的辛苦可以从古诗《蚕妇》窥得一二:昨日入城市,归来泪满巾。...
    输过败过但没怕过阅读 827评论 3 3