java中如何使用HttpClient調(diào)用接口
java使用HttpClient調(diào)用接口
HttpClient 提供的主要的功能
(1)實(shí)現(xiàn)了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)
(2)支持自動轉(zhuǎn)向
(3)支持 HTTPS 協(xié)議
(4)支持代理服務(wù)器等
直接言歸正傳了?。。?!上代碼
public static String sendPutForm(String url, Map<String,String> map, String encoding) throws ParseException, IOException {
String body = "";
// 打印了一下我推送的json數(shù)據(jù)
log.info("我推送的json數(shù)據(jù):" + map);
log.info("我推送的url:" + url);
CloseableHttpResponse response = null;
///獲得Http客戶端
CloseableHttpClient client = HttpClients.createDefault();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 配置信息
// 設(shè)置連接超時(shí)時(shí)間(單位毫秒)
// 設(shè)置請求超時(shí)時(shí)間(單位毫秒)
// socket讀寫超時(shí)時(shí)間(單位毫秒)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000).setConnectionRequestTimeout(50000)
.setSocketTimeout(50000).build();
// 向指定資源位置上傳內(nèi)容// 創(chuàng)建Post請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setEntity(formEntity);
try {
response = client.execute(httpPost);
// 通過response中的getEntity()方法獲取返回值
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
httpPost.abort();
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
log.info("body:" + body);
return body;
}
代碼其實(shí)就是這么多,還有好多形式。大家可以參考寫一下。
java的HttpClient調(diào)用遠(yuǎn)程接口
httpClient比jdk自帶的URLConection更加易用和方便,這里介紹一下使用httpClient來調(diào)用遠(yuǎn)程接口。
首先導(dǎo)入相關(guān)的依賴包:
<!-- httpClient --> ?? ??? ?<dependency> ?? ??? ? ? ?<groupId>org.apache.httpcomponents</groupId> ?? ??? ? ? ?<artifactId>httpclient</artifactId> ?? ??? ? ? ?<version>4.5.3</version> ?? ??? ?</dependency>
使用方法
1,創(chuàng)建HttpClient對象;
2,指定請求URL,并創(chuàng)建請求對象,如果是get請求則創(chuàng)建HttpGet對象,post則創(chuàng)建HttpPost對象;
3,如果請求帶有參數(shù),對于get請求可直接在URL中加上參數(shù)請求,或者使用setParam(HetpParams params)方法設(shè)置參數(shù),對于HttpPost請求,可使用setParam(HetpParams params)方法或者調(diào)用setEntity(HttpEntity entity)方法設(shè)置參數(shù);
4,調(diào)用httpClient的execute(HttpUriRequest request)執(zhí)行請求,返回結(jié)果是一個(gè)response對象;
5,通過response的getHeaders(String name)或getAllHeaders()可獲得請求頭部信息,getEntity()方法獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。
實(shí)例
我使用了property文件來保存不同API對應(yīng)的鏈接,也可以除去properties文件的讀取代碼,直接將變量 API換成所需URL
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
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;
public class APIUtil {
/**
* 返回API調(diào)用結(jié)果
* @param APIName 接口在api.properties中的名稱
* @param params 訪問api所需的參數(shù)及參數(shù)值
* @return 此處返回的是JSON格式的數(shù)據(jù)
*/
public static String API(String APIName, Map<String, Object> params) {
String content = "";
//請求結(jié)果
CloseableHttpResponse response = null;
//實(shí)例化httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//讀取配置文件的URL
Properties properties = new Properties();
URL fileURL = APIUtil.class.getClassLoader().getResource("api.properties");
properties.load(new FileInputStream(new File(fileURL.getFile())));
String API = properties.getProperty(APIName);
//構(gòu)造url請求
StringBuilder url = new StringBuilder(API);
if(params!=null && params.size()>0) {
url.append("?");
for(Map.Entry<String, Object> entry : params.entrySet()) {
url.append(entry.getKey()+"="+entry.getValue()+"&");
}
url.substring(0, url.length()-1);
}
//實(shí)例化get方法
HttpGet httpget = new HttpGet(url.toString());
//執(zhí)行g(shù)et請求
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode()==200) {
content = EntityUtils.toString(response.getEntity(),"utf-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}執(zhí)行完畢后返回API提供的數(shù)據(jù)。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot 基于注解的 Redis 緩存使用詳解
本篇文章主要介紹了Spring Boot 基于注解的 Redis 緩存使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05
Java內(nèi)存模型相關(guān)知識總結(jié)
這篇文章主要介紹了Java內(nèi)存模型相關(guān)知識總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Java實(shí)現(xiàn)發(fā)送短信驗(yàn)證碼功能
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)發(fā)送短信驗(yàn)證碼功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
圖解Java經(jīng)典算法希爾排序的原理與實(shí)現(xiàn)
希爾排序是希爾(Donald Shell)于1959年提出的一種排序算法。希爾排序也是一種插入排序,它是簡單插入排序經(jīng)過改進(jìn)之后的一個(gè)更高效的版本,也稱為縮小增量排序,同時(shí)該算法是沖破O(n2)的第一批算法之一。本文會以圖解的方式詳細(xì)介紹希爾排序的基本思想及其代碼實(shí)現(xiàn)2022-09-09
SpringBoot使用@Cacheable出現(xiàn)預(yù)覽工具亂碼的解決方法
直接使用注解進(jìn)行緩存數(shù)據(jù),我們再使用工具去預(yù)覽存儲的數(shù)據(jù)時(shí)發(fā)現(xiàn)是亂碼,這是由于默認(rèn)序列化的問題,所以接下來將給大家介紹一下SpringBoot使用@Cacheable出現(xiàn)預(yù)覽工具亂碼的解決方法,需要的朋友可以參考下2023-10-10
Spring動態(tài)注冊多數(shù)據(jù)源的實(shí)現(xiàn)方法
這篇文章主要介紹了Spring動態(tài)注冊多數(shù)據(jù)源的實(shí)現(xiàn)方法,小編覺的挺不錯(cuò)的,現(xiàn)分享到腳本之家平臺,需要的朋友可以參考下2018-01-01

