2018-04-26

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
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.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.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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.junit.Test;

public class HttpClientTest {

@Test
public void jUnitTest() {
    get();
}

/**
 * HttpClient連接SSL
 */
public void ssl() {
    CloseableHttpClient httpclient = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore"));
        try {
            // 加載keyStore d:\\tomcat.keystore  
            trustStore.load(instream, "123456".toCharArray());
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }
        // 相信自己的CA和所有自簽名的證書
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // 只允許使用TLSv1協(xié)議
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        // 創(chuàng)建http請求(get方式)
        HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
        System.out.println("executing request" + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                System.out.println(EntityUtils.toString(entity));
                EntityUtils.consume(entity);
            }
        } finally {
            response.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } finally {
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * post方式提交表單(模擬用戶登錄請求)
 */
public void postForm() {
    // 創(chuàng)建默認(rèn)的httpClient實(shí)例.  
    CloseableHttpClient httpclient = HttpClients.createDefault();
    // 創(chuàng)建httppost  
    HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
    // 創(chuàng)建參數(shù)隊(duì)列  
    List<namevaluepair> formparams = new ArrayList<namevaluepair>();
    formparams.add(new BasicNameValuePair("username", "admin"));
    formparams.add(new BasicNameValuePair("password", "123456"));
    UrlEncodedFormEntity uefEntity;
    try {
        uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(uefEntity);
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println("--------------------------------------");
                System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                System.out.println("--------------------------------------");
            }
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 關(guān)閉連接,釋放資源  
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 發(fā)送 post請求訪問本地應(yīng)用并根據(jù)傳遞參數(shù)不同返回不同結(jié)果
 */
public void post() {
    // 創(chuàng)建默認(rèn)的httpClient實(shí)例.  
    CloseableHttpClient httpclient = HttpClients.createDefault();
    // 創(chuàng)建httppost  
    HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
    // 創(chuàng)建參數(shù)隊(duì)列  
    List<namevaluepair> formparams = new ArrayList<namevaluepair>();
    formparams.add(new BasicNameValuePair("type", "house"));
    UrlEncodedFormEntity uefEntity;
    try {
        uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(uefEntity);
        System.out.println("executing request " + httppost.getURI());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out.println("--------------------------------------");
                System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                System.out.println("--------------------------------------");
            }
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 關(guān)閉連接,釋放資源  
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 發(fā)送 get請求
 */
public void get() {
    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請求.  
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            // 獲取響應(yīng)實(shí)體  
            HttpEntity entity = response.getEntity();
            System.out.println("--------------------------------------");
            // 打印響應(yīng)狀態(tài)  
            System.out.println(response.getStatusLine());
            if (entity != null) {
                // 打印響應(yīng)內(nèi)容長度  
                System.out.println("Response content length: " + entity.getContentLength());
                // 打印響應(yīng)內(nèi)容  
                System.out.println("Response content: " + EntityUtils.toString(entity));
            }
            System.out.println("------------------------------------");
        } 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();
        }
    }
}

/**
 * 上傳文件
 */
public void upload() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");

        FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子屎鳍,更是在濱河造成了極大的恐慌芒粹,老刑警劉巖愉择,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件籍凝,死亡現(xiàn)場離奇詭異屠缭,居然都是意外死亡骡和,警方通過查閱死者的電腦和手機(jī)相赁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來慰于,“玉大人钮科,你說我怎么就攤上這事∑旁” “怎么了绵脯?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我蛆挫,道長赃承,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任悴侵,我火速辦了婚禮瞧剖,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘可免。我一直安慰自己抓于,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布巴元。 她就那樣靜靜地躺著毡咏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪逮刨。 梳的紋絲不亂的頭發(fā)上呕缭,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天,我揣著相機(jī)與錄音修己,去河邊找鬼恢总。 笑死,一個(gè)胖子當(dāng)著我的面吹牛睬愤,可吹牛的內(nèi)容都是我干的片仿。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼尤辱,長吁一口氣:“原來是場噩夢啊……” “哼砂豌!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起光督,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤阳距,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后结借,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體筐摘,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年船老,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了咖熟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,981評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡柳畔,死狀恐怖馍管,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情薪韩,我是刑警寧澤咽斧,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布堪置,位于F島的核電站,受9級特大地震影響张惹,放射性物質(zhì)發(fā)生泄漏舀锨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一宛逗、第九天 我趴在偏房一處隱蔽的房頂上張望坎匿。 院中可真熱鬧,春花似錦雷激、人聲如沸替蔬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽承桥。三九已至,卻和暖如春根悼,著一層夾襖步出監(jiān)牢的瞬間凶异,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工挤巡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留剩彬,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓矿卑,卻偏偏與公主長得像喉恋,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子母廷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容

  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光劍書架上的書閱讀 3,881評論 2 8
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理轻黑,服務(wù)發(fā)現(xiàn),斷路器琴昆,智...
    卡卡羅2017閱讀 134,657評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,811評論 6 342
  • 繁星之城 或擦肩而過 或回眸一笑 或十指緊扣 繁星之城 也許是隨意一瞥 也許是無言一笑 也許是緊緊相擁 繁星之城 ...
    坡上風(fēng)閱讀 283評論 0 0
  • 三點(diǎn)收獲: 1氓鄙、心比形式更重要(教練技術(shù)),能量場能影響到別人椎咧,能讓人安定玖详,教練安定好自己的身心后把介,影響到被教練者...
    wangzi04閱讀 276評論 0 1