您好,登錄后才能下訂單哦!
這篇文章主要介紹“java怎么使用HttpClient調(diào)用接口”,在日常操作中,相信很多人在java怎么使用HttpClient調(diào)用接口問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”java怎么使用HttpClient調(diào)用接口”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
(1)實現(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è)置請求超時時間(單位毫秒) // socket讀寫超時時間(單位毫秒) 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; }
代碼其實就是這么多,還有好多形式。大家可以參考寫一下。
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é)果是一個response對象;
5,通過response的getHeaders(String name)或getAllHeaders()可獲得請求頭部信息,getEntity()方法獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。
我使用了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; //實例化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); } //實例化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ù)。
到此,關(guān)于“java怎么使用HttpClient調(diào)用接口”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。