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 {
    /*
     * 請(qǐng)求步驟 使用幫助類HttpClients創(chuàng)建CloseableHttpClient對(duì)象.
     * 基于要發(fā)送的HTTP請(qǐng)求類型創(chuàng)建HttpGet或者HttpPost實(shí)例. 使用addHeader方法添加請(qǐng)求頭部,諸如User-Agent,
     * Accept-Encoding等參數(shù). 可調(diào)用HttpGet、HttpPost共同的setParams(HetpParams
     * params)方法來添加請(qǐng)求參數(shù);對(duì)于HttpPost對(duì)象而言,也可調(diào)用setEntity(HttpEntity
     * entity)方法來設(shè)置請(qǐng)求參數(shù)。 通過執(zhí)行此HttpGet或者HttpPost請(qǐng)求獲取CloseableHttpResponse實(shí)例
     * 從此CloseableHttpResponse實(shí)例中獲取狀態(tài)碼,錯(cuò)誤信息,以及響應(yīng)頁(yè)面等等. 釋放連接。無論執(zhí)行方法是否成功,都必須釋放連接
     * 
     * 作者:AnakinSky 鏈接:http://www.itdecent.cn/p/99c627c6aa9b 來源:簡(jiǎn)書
     * 著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
     */

    @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();// 設(shè)置請(qǐng)求和傳輸超時(shí)時(shí)間
            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("班級(jí)類型");
        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();// 設(shè)置請(qǐng)求和傳輸超時(shí)時(shí)間
            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("班級(jí)類型");
        Assert.assertEquals(true, isSuccess);
        // return response.toString();
        
    }

    public void httpGet() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 創(chuàng)建httpget.
            HttpGet httpget = new HttpGet("http://www.baidu.com/");
            System.out.println("executing request " + httpget.getURI());
            // 執(zhí)行g(shù)et請(qǐng)求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 獲取響應(yīng)實(shí)體
                HttpEntity entity = response.getEntity();
                // 打印響應(yīng)狀態(tài)
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印響應(yīng)內(nèi)容長(zhǎng)度
                    System.out.println("Response content length: "
                            + entity.getContentLength());
                    // 打印響應(yīng)內(nèi)容
                    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 {
            // 關(guān)閉連接,釋放資源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 昨天發(fā)生的糟心是太讓我心情郁悶了,但是我不想把事情寫出來,我這個(gè)人好像不是那么愛訴說的人,可能覺得我說了反而更加難...
    LilyM_海蕾閱讀 169評(píng)論 0 1
  • 1 今天運(yùn)動(dòng),空跳,加上脖頸操。這段時(shí)間只能先考慮省課題申報(bào)。沒有閱讀時(shí)間。今天還沒聽書。 上課五節(jié),完成玩轉(zhuǎn)語文...
    躲進(jìn)小樓看燈火閱讀 248評(píng)論 0 0
  • 每個(gè)人都在不停的尋找自己的位置和方向,或前或后或左或右 7歲時(shí) 有人和小伙伴在歡聲笑語 有人與顏真卿歐陽詢?cè)?..
    綰之微木閱讀 228評(píng)論 0 0
  • 文章看多了,應(yīng)該欣賞一些美,心情會(huì)更美麗,這是我收集的一些童真,希望朋友們能像她們的笑容一樣,在快節(jié)奏的生活中像她...
    閆騰影像閱讀 277評(píng)論 0 0
  • 記憶中,我生活所在的地方,幾乎沒有以養(yǎng)蠶為生的人。養(yǎng)蠶人的辛苦可以從古詩(shī)《蠶婦》窺得一二:昨日入城市,歸來淚滿巾。...
    輸過敗過但沒怕過閱讀 1,009評(píng)論 3 3

友情鏈接更多精彩內(nèi)容