Java如何實(shí)現(xiàn)調(diào)用外部Api
Java調(diào)用外部Api
在日常開發(fā)的時(shí)候,經(jīng)常會(huì)遇到需要調(diào)用別人的接口的場景。但是每次需要的時(shí)候,都需要百度,很麻煩,所以這里總結(jié)一下,經(jīng)常調(diào)用的方法。
1.含有文件的post請(qǐng)求
public static String requestOCRForHttp(String url, Map<String, String> requestParams, String filePathAndName) throws Exception { String result = null; CloseableHttpClient httpClient = HttpClients.createDefault(); /** HttpPost */ HttpPost httpPost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); // 建立多文件實(shí)例 FileBody filebody = new FileBody(new File(filePathAndName)); reqEntity.addPart("pic", filebody);// upload為請(qǐng)求后臺(tái)的File upload; for (String key : requestParams.keySet()) { String value = requestParams.get(key); reqEntity.addPart(key, new StringBody(value, Charset.forName("utf-8"))); } httpPost.setEntity(reqEntity); // 設(shè)置實(shí)體 /** HttpResponse */ CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity, "utf-8"); EntityUtils.consume(httpEntity); } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.info("## release resouce error ##" + e); } } return result; }
2.單純的Json
public static String sendHttpPost(String url, String JSONBody) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(JSONBody)); CloseableHttpResponse response = httpClient.execute(httpPost); // System.out.println(response.getStatusLine().getStatusCode() + "\n"); HttpEntity entity = response.getEntity(); String responseContent = EntityUtils.toString(entity, "UTF-8"); // System.out.println(responseContent); response.close(); httpClient.close(); return responseContent; }
3.String參數(shù)
public static String requestOCRForHttp(String url, Map<String, String> requestParams) throws Exception { String result = null; CloseableHttpClient httpClient = HttpClients.createDefault(); /** HttpPost */ HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); Iterator<Entry<String, String>> it = requestParams.entrySet().iterator(); // System.out.println(params.toString()); while (it.hasNext()) { Entry<String, String> en = it.next(); String key = en.getKey(); String value = en.getValue(); if (value != null) { params.add(new BasicNameValuePair(key, value)); } } httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); /** HttpResponse */ CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity, "utf-8"); EntityUtils.consume(httpEntity); } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.info("## release resouce error ##" + e); } } return result; }
Java對(duì)接外部API這個(gè)問題
有一個(gè)小學(xué)妹來問我可以將我其他項(xiàng)目的api接入到我現(xiàn)在的項(xiàng)目中嗎?我回答“可以”!
需求提出
那么拿到一個(gè)需求首先話不多說先分析這個(gè)需求的整體思路!需求上面大概有介紹,這里我更深入化的說明一下。
對(duì)接外部api接口就是說我在A項(xiàng)目寫了一個(gè)接口時(shí)我的B項(xiàng)目需要到A這個(gè)接口的數(shù)據(jù),那么在A項(xiàng)目上線的基礎(chǔ)上使用B項(xiàng)目去調(diào)用A項(xiàng)目的這個(gè)所需的接口,如下圖:
其實(shí)對(duì)接外部api就是這么一個(gè)過程,當(dāng)然我們拿到外部數(shù)據(jù)后面的操作都是由自己去自由發(fā)揮了,比如將讀取到的數(shù)據(jù)來顯示在這個(gè)項(xiàng)目中去給前端顯示?;蛘叽嫒霐?shù)據(jù)庫等等。
解決思路
上面已經(jīng)理解了調(diào)用的的思路,有了思路就好解決,現(xiàn)在很多的外部api接口可以給開發(fā)時(shí)帶來便利,當(dāng)然,調(diào)用的方式可能也會(huì)有稍些不同,比如手機(jī)號(hào)查詢歸屬地、郵箱等等。
像這種的一般都是有官方文檔可以給我們,很方便。
但是我們?nèi)フ{(diào)用自己的api又不是在一個(gè)項(xiàng)目中的那就要想想怎么實(shí)現(xiàn)了。
話不多說我就拿我之前寫了一個(gè)DEMO中的數(shù)據(jù)吧,剛好項(xiàng)目還在線上。
編碼
package edu.controller; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.aliyun.oss.HttpMethod; import edu.entity.EventVo; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author Fujii * @Date 2021-10-11 23:12 * @Version SpringBoot 2.2.2 * @projectName 調(diào)用外部api接口 */ @RestController public class BackEndApiDemo { @GetMapping("apiList") public Map<String,Object> getByApiList(){ //這里先創(chuàng)建一個(gè)map用于返回api格式 Map<String,Object> mapList = new HashMap<>(); //1.我們是要去調(diào)用外部api,那么肯定要有一個(gè)外部api的地址,這里我是拿我的DEMO作為數(shù)據(jù)傳輸 String apiURL = "這里直接放入你的api接口即可,我的api就不展示了,請(qǐng)諒解!"; //2.這里有幾種方式,你們?nèi)ピ嚵诉^后會(huì)發(fā)現(xiàn)不只有GET,這里因?yàn)槲覀兪侨カ@取數(shù)據(jù),所以是用GET HttpMethod method = HttpMethod.GET; //用于接口返回的JSONObject() LinkedMultiValueMap map = new LinkedMultiValueMap(); //json接收數(shù)據(jù) JSONObject urlMethod = client(apiURL,method,map); JSONObject jsonObject = JSONObject.parseObject(urlMethod.toJSONString()); JSONArray object = JSONObject.parseArray(jsonObject.get("data").toString()); if (jsonObject!=null){ List<EventVo> list = JSONArray.parseArray(object.toJSONString(), EventVo.class); mapList.put("list",list); mapList.put("code",200); mapList.put("msg", "獲取成功!"); }else{ mapList.put("code",500); mapList.put("msg", "獲取失敗!"); return mapList; } return mapList; } //注意:因?yàn)槭菧y試,所有我所有內(nèi)容全部寫在一個(gè)文件內(nèi)方便展示清晰,正規(guī)寫法應(yīng)寫在服務(wù)層 private JSONObject client(String url, HttpMethod method, LinkedMultiValueMap params) { RestTemplate template = new RestTemplate(); ResponseEntity<JSONObject> response = template.getForEntity(url, JSONObject.class); return response.getBody(); } }
測試
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring的@CrossOrigin注解使用與CrossFilter對(duì)象自定義詳解
這篇文章主要介紹了Spring的@CrossOrigin注解使用與CrossFilter對(duì)象自定義詳解,跨域,指的是瀏覽器不能執(zhí)行其他網(wǎng)站的腳本,它是由瀏覽器的同源策略造成的,是瀏覽器施加的安全限制,所謂同源是指,域名,協(xié)議,端口均相同,需要的朋友可以參考下2023-12-12springboot實(shí)現(xiàn)學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了springboot實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07