HttpClientUtil工具類

package com.taotao.utils;

import com.thoughtworks.xstream.XStream;

import com.thoughtworks.xstream.io.xml.DomDriver;

import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

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.client.methods.HttpUriRequest;

import org.apache.http.entity.StringEntity;

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 java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

/**

* @Package com.taotao.utils

* @User 12428

* @Date 2018/3/23 8:36

*/

public class HttpClientUtil {

private static final StringCHARSET_UTF_8 ="UTF-8";

private static final StringCONTENT_TYPE_JSON ="application/json";

private static final StringCONTENT_TYPE_XML ="text/xml";

/**

* 發(fā)送get請(qǐng)求

? ? * @param url

? ? * @return

? ? */

? ? public static String get(String url) {

String res =null;

CloseableHttpClient httpClient = HttpClients.createDefault();

try {

HttpGet httpGet =new HttpGet(url);

res =execute(httpClient, httpGet);

}finally {

doHttpClientClose(httpClient);

}

return res;

}

/**

* 發(fā)送post請(qǐng)求

? ? * @param url? ? post url

? ? * @param params post參數(shù)

? ? * @return

? ? */

? ? public static String post(String url, Map params) {

String res =null;

CloseableHttpClient httpClient = HttpClients.createDefault();

try {

HttpPost httpPost =httpPostHandler(url, params);

res =execute(httpClient, httpPost);

}finally {

doHttpClientClose(httpClient);

}

return res;

}

/**

* post json數(shù)據(jù)

? ? * @param url

? ? * @param jsonStr

? ? * @return

? ? */

? ? public static String postJson(String url, String jsonStr) {

String res =null;

CloseableHttpClient httpClient = HttpClients.createDefault();

try {

HttpPost httpPost =new HttpPost(url);

StringEntity stringEntity;

try {

stringEntity =new StringEntity(jsonStr);

}catch (UnsupportedEncodingException e) {

return null;

}

httpPost.setHeader("Content-Type",CONTENT_TYPE_JSON);

httpPost.setEntity(stringEntity);

res =execute(httpClient, httpPost);

}finally {

doHttpClientClose(httpClient);

}

return res;

}

/**

* post xml數(shù)據(jù)

? ? * @param url

? ? * @param xmlObj

? ? * @return

? ? */

? ? public static String postXml(String url, Object xmlObj) {

String res =null;

CloseableHttpClient httpClient = HttpClients.createDefault();

try {

HttpPost httpPost =new HttpPost(url);

//解決XStream對(duì)出現(xiàn)雙下劃線的bug

? ? ? ? ? ? XStream xStreamForRequestPostData =new XStream(new DomDriver("UTF-8",new XmlFriendlyNameCoder("-_","_")));

//將要提交給API的數(shù)據(jù)對(duì)象轉(zhuǎn)換成XML格式數(shù)據(jù)Post給API

? ? ? ? ? ? String postDataXML = xStreamForRequestPostData.toXML(xmlObj);

//得指明使用UTF-8編碼修己,否則到API服務(wù)器XML的中文不能被成功識(shí)別

? ? ? ? ? ? StringEntity postEntity =new StringEntity(postDataXML,"UTF-8");

httpPost.addHeader("Content-Type",CONTENT_TYPE_XML);

httpPost.setEntity(postEntity);

res =execute(httpClient, httpPost);

}finally {

doHttpClientClose(httpClient);

}

return res;

}

private static HttpPost httpPostHandler(String url, Map params) {

HttpPost httpPost =new HttpPost(url);

List nvps =new ArrayList<>();

for (Map.Entry entry : params.entrySet()) {

nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

}

try {

httpPost.setEntity(new UrlEncodedFormEntity(nvps,CHARSET_UTF_8));

}catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return httpPost;

}

private static String execute(CloseableHttpClient httpClient, HttpUriRequest httpGetOrPost) {

String res =null;

CloseableHttpResponse response =null;

try {

response = httpClient.execute(httpGetOrPost);

HttpEntity entity = response.getEntity();

res = EntityUtils.toString(entity,CHARSET_UTF_8);

}catch (IOException e) {

e.printStackTrace();

}finally {

doResponseClose(response);

}

return res;

}

private static void doHttpClientClose(CloseableHttpClient httpClient) {

if (httpClient !=null) {

try {

httpClient.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

private static void doResponseClose(CloseableHttpResponse response) {

if (response !=null) {

try {

response.close();

}catch (IOException e) {

e.printStackTrace();

}

}

}

//? ? public static void main(String[] args) {

//? ? ? ? String url = "";

//? ? ? ? String res = get(url);

//? ? ? ? System.out.println(res);

//? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末姿染,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子菌湃,更是在濱河造成了極大的恐慌芯肤,老刑警劉巖巷折,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異崖咨,居然都是意外死亡锻拘,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門击蹲,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逊拍,“玉大人,你說我怎么就攤上這事际邻⌒旧ィ” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵世曾,是天一觀的道長(zhǎng)缨恒。 經(jīng)常有香客問我,道長(zhǎng)轮听,這世上最難降的妖魔是什么骗露? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮血巍,結(jié)果婚禮上萧锉,老公的妹妹穿的比我還像新娘。我一直安慰自己述寡,他們只是感情好柿隙,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著鲫凶,像睡著了一般禀崖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上螟炫,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天波附,我揣著相機(jī)與錄音,去河邊找鬼。 笑死掸屡,一個(gè)胖子當(dāng)著我的面吹牛封寞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播仅财,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼钥星,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了满着?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤贯莺,失蹤者是張志新(化名)和其女友劉穎风喇,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缕探,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡魂莫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了爹耗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片耙考。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖潭兽,靈堂內(nèi)的尸體忽然破棺而出倦始,到底是詐尸還是另有隱情,我是刑警寧澤山卦,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布鞋邑,位于F島的核電站,受9級(jí)特大地震影響账蓉,放射性物質(zhì)發(fā)生泄漏枚碗。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一铸本、第九天 我趴在偏房一處隱蔽的房頂上張望肮雨。 院中可真熱鬧,春花似錦箱玷、人聲如沸怨规。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽椅亚。三九已至,卻和暖如春舱污,著一層夾襖步出監(jiān)牢的瞬間呀舔,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留媚赖,地道東北人霜瘪。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像惧磺,于是被迫代替她去往敵國(guó)和親颖对。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

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