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)文章
Seata AT模式TransactionHook被刪除探究
這篇文章主要為大家介紹了Seata AT模式TransactionHook被刪除探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11Java深入學(xué)習(xí)圖形用戶界面GUI之事件處理
這篇文章主要介紹了基于Java GUI 事件處理方式,一個(gè)圖形界面制作完成了,在程序開發(fā)中只是完成了起步的工作。要想讓一個(gè)組件都發(fā)揮自己的作用.就必須對所有的組件進(jìn)行事件處理2022-05-05Java中List.contains(Object?object)方法使用
本文主要介紹了Java中List.contains(Object?object)方法,使用List.contains(Object?object)方法判斷ArrayList是否包含一個(gè)元素對象,感興趣的可以了解一下2022-04-04JAVA新手小白學(xué)正則表達(dá)式、包裝類、自動裝箱/自動拆箱以及BigDecimal
這篇文章主要給大家介紹了關(guān)于JAVA新手小白學(xué)正則表達(dá)式、包裝類、自動裝箱/自動拆箱以及BigDecimal的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03Java 為什么要避免使用finalizer和Cleaner
這篇文章主要介紹了Java 為什么要避免使用finalizer和Cleaner,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-03-03Spark調(diào)優(yōu)多線程并行處理任務(wù)實(shí)現(xiàn)方式
這篇文章主要介紹了Spark調(diào)優(yōu)多線程并行處理任務(wù)實(shí)現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08