Java如何實現(xiàn)調(diào)用外部Api
Java調(diào)用外部Api
在日常開發(fā)的時候,經(jīng)常會遇到需要調(diào)用別人的接口的場景。但是每次需要的時候,都需要百度,很麻煩,所以這里總結(jié)一下,經(jīng)常調(diào)用的方法。
1.含有文件的post請求
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(); // 建立多文件實例
FileBody filebody = new FileBody(new File(filePathAndName));
reqEntity.addPart("pic", filebody);// upload為請求后臺的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è)置實體
/** 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對接外部API這個問題
有一個小學妹來問我可以將我其他項目的api接入到我現(xiàn)在的項目中嗎?我回答“可以”!
需求提出
那么拿到一個需求首先話不多說先分析這個需求的整體思路!需求上面大概有介紹,這里我更深入化的說明一下。
對接外部api接口就是說我在A項目寫了一個接口時我的B項目需要到A這個接口的數(shù)據(jù),那么在A項目上線的基礎(chǔ)上使用B項目去調(diào)用A項目的這個所需的接口,如下圖:

其實對接外部api就是這么一個過程,當然我們拿到外部數(shù)據(jù)后面的操作都是由自己去自由發(fā)揮了,比如將讀取到的數(shù)據(jù)來顯示在這個項目中去給前端顯示?;蛘叽嫒霐?shù)據(jù)庫等等。
解決思路
上面已經(jīng)理解了調(diào)用的的思路,有了思路就好解決,現(xiàn)在很多的外部api接口可以給開發(fā)時帶來便利,當然,調(diào)用的方式可能也會有稍些不同,比如手機號查詢歸屬地、郵箱等等。
像這種的一般都是有官方文檔可以給我們,很方便。
但是我們?nèi)フ{(diào)用自己的api又不是在一個項目中的那就要想想怎么實現(xiàn)了。
話不多說我就拿我之前寫了一個DEMO中的數(shù)據(jù)吧,剛好項目還在線上。
編碼
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)建一個map用于返回api格式
Map<String,Object> mapList = new HashMap<>();
//1.我們是要去調(diào)用外部api,那么肯定要有一個外部api的地址,這里我是拿我的DEMO作為數(shù)據(jù)傳輸
String apiURL = "這里直接放入你的api接口即可,我的api就不展示了,請諒解!";
//2.這里有幾種方式,你們?nèi)ピ嚵诉^后會發(fā)現(xiàn)不只有GET,這里因為我們是去獲取數(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;
}
//注意:因為是測試,所有我所有內(nèi)容全部寫在一個文件內(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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring的@CrossOrigin注解使用與CrossFilter對象自定義詳解
這篇文章主要介紹了Spring的@CrossOrigin注解使用與CrossFilter對象自定義詳解,跨域,指的是瀏覽器不能執(zhí)行其他網(wǎng)站的腳本,它是由瀏覽器的同源策略造成的,是瀏覽器施加的安全限制,所謂同源是指,域名,協(xié)議,端口均相同,需要的朋友可以參考下2023-12-12
springboot實現(xiàn)學生管理系統(tǒng)
這篇文章主要為大家詳細介紹了springboot實現(xiàn)學生管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07

