<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Java 調(diào)用第三方接口,實戰(zhàn)來了!

          共 4770字,需瀏覽 10分鐘

           ·

          2022-05-21 14:11

          在項目開發(fā)中經(jīng)常會遇到調(diào)用第三方接口的情況,比如說調(diào)用第三方的天氣預(yù)報接口。

          1、準(zhǔn)備工作:

          在項目的工具包下導(dǎo)入HttpClientUtil這個工具類,或者也可以使用Spring框架的restTemplate來調(diào)用,上面有調(diào)用接口的方法【分為Get和Post方式的有參和無參調(diào)用】:

          package?com.njsc.credit.util;
          ?
          import?java.io.IOException;
          import?java.net.URI;
          import?java.util.ArrayList;
          import?java.util.List;
          import?java.util.Map;
          ?
          import?org.apache.http.NameValuePair;
          import?org.apache.http.client.entity.UrlEncodedFormEntity;
          import?org.apache.http.client.methods.CloseableHttpResponse;
          import?org.apache.http.client.methods.HttpGet;
          import?org.apache.http.client.methods.HttpPost;
          import?org.apache.http.client.utils.URIBuilder;
          import?org.apache.http.entity.ContentType;
          import?org.apache.http.entity.StringEntity;
          import?org.apache.http.impl.client.CloseableHttpClient;
          import?org.apache.http.impl.client.HttpClients;
          import?org.apache.http.message.BasicNameValuePair;
          import?org.apache.http.util.EntityUtils;
          ?
          public?class?HttpClientUtil?{
          ?
          ?/**
          ??*?帶參數(shù)的get請求
          ??*?@param?url
          ??*?@param?param
          ??*?@return?String
          ??*/
          ?public?static?String?doGet(String?url,?Map?param)?{
          ??//?創(chuàng)建Httpclient對象
          ??CloseableHttpClient?httpclient?=?HttpClients.createDefault();
          ?
          ??String?resultString?=?"";
          ??CloseableHttpResponse?response?=?null;
          ??try?{
          ???//?創(chuàng)建uri
          ???URIBuilder?builder?=?new?URIBuilder(url);
          ???if?(param?!=?null)?{
          ????for?(String?key?:?param.keySet())?{
          ?????builder.addParameter(key,?param.get(key));
          ????}
          ???}
          ???URI?uri?=?builder.build();
          ???//?創(chuàng)建http?GET請求
          ???HttpGet?httpGet?=?new?HttpGet(uri);
          ???//?執(zhí)行請求
          ???response?=?httpclient.execute(httpGet);
          ???//?判斷返回狀態(tài)是否為200
          ???if?(response.getStatusLine().getStatusCode()?==?200)?{
          ????resultString?=?EntityUtils.toString(response.getEntity(),?"UTF-8");
          ???}
          ??}?catch?(Exception?e)?{
          ???e.printStackTrace();
          ??}?finally?{
          ???try?{
          ????if?(response?!=?null)?{
          ?????response.close();
          ????}
          ????httpclient.close();
          ???}?catch?(IOException?e)?{
          ????e.printStackTrace();
          ???}
          ??}
          ??return?resultString;
          ?}
          ?
          ?/**
          ??*?不帶參數(shù)的get請求
          ??*?@param?url
          ??*?@return?String
          ??*/
          ?public?static?String?doGet(String?url)?{
          ??return?doGet(url,?null);
          ?}
          ?
          ?/**
          ??*?帶參數(shù)的post請求
          ??*?@param?url
          ??*?@param?param
          ??*?@return?String
          ??*/
          ?public?static?String?doPost(String?url,?Map?param)?{
          ??//?創(chuàng)建Httpclient對象
          ??CloseableHttpClient?httpClient?=?HttpClients.createDefault();
          ??CloseableHttpResponse?response?=?null;
          ??String?resultString?=?"";
          ??try?{
          ???//?創(chuàng)建Http?Post請求
          ???HttpPost?httpPost?=?new?HttpPost(url);
          ???//?創(chuàng)建參數(shù)列表
          ???if?(param?!=?null)?{
          ????List?paramList?=?new?ArrayList<>();
          ????for?(String?key?:?param.keySet())?{
          ?????paramList.add(new?BasicNameValuePair(key,?param.get(key)));
          ????}
          ????//?模擬表單
          ????UrlEncodedFormEntity?entity?=?new?UrlEncodedFormEntity(paramList);
          ????httpPost.setEntity(entity);
          ???}
          ???//?執(zhí)行http請求
          ???response?=?httpClient.execute(httpPost);
          ???resultString?=?EntityUtils.toString(response.getEntity(),?"utf-8");
          ??}?catch?(Exception?e)?{
          ???e.printStackTrace();
          ??}?finally?{
          ???try?{
          ????response.close();
          ???}?catch?(IOException?e)?{
          ????e.printStackTrace();
          ???}
          ??}
          ??return?resultString;
          ?}
          ?
          ?/**
          ??*?不帶參數(shù)的post請求
          ??*?@param?url
          ??*?@return?String
          ??*/
          ?public?static?String?doPost(String?url)?{
          ??return?doPost(url,?null);
          ?}
          ?
          ?/**
          ??*?傳送json類型的post請求
          ??*?@param?url
          ??*?@param?json
          ??*?@return?String
          ??*/
          ?public?static?String?doPostJson(String?url,?String?json)?{
          ??//?創(chuàng)建Httpclient對象
          ??CloseableHttpClient?httpClient?=?HttpClients.createDefault();
          ??CloseableHttpResponse?response?=?null;
          ??String?resultString?=?"";
          ??try?{
          ???//?創(chuàng)建Http?Post請求
          ???HttpPost?httpPost?=?new?HttpPost(url);
          ???//?創(chuàng)建請求內(nèi)容
          ???StringEntity?entity?=?new?StringEntity(json,?ContentType.APPLICATION_JSON);
          ???httpPost.setEntity(entity);
          ???//?執(zhí)行http請求
          ???response?=?httpClient.execute(httpPost);
          ???resultString?=?EntityUtils.toString(response.getEntity(),?"utf-8");
          ??}?catch?(Exception?e)?{
          ???e.printStackTrace();
          ??}?finally?{
          ???try?{
          ????response.close();
          ???}?catch?(IOException?e)?{
          ????e.printStackTrace();
          ???}
          ??}
          ??return?resultString;
          ?}
          }

          2、創(chuàng)建url和訪問key 以及參數(shù)等:

          代碼如下:

          /**
          ?*?聚合接口校驗身份證
          ?*?@param?idCard
          ?*?@param?realName
          ?*?@return?boolean
          ?*/
          public?boolean?identityCheck(String?idCard,?String?realName){
          ?logger.info("-----------------調(diào)用聚合數(shù)據(jù)?身份證驗證API?BEGIN--------------->");
          ?String?key?=?"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
          ?String?url?=?"http://op.juhe.cn/idcard/query"?+?"?key="?+?key?+?"&idcard="?+?idCard?+?"&realname="?+?realName;
          ?logger.info("請求url:"?+?url);
          ?boolean?match?=?false;?//是否匹配
          ?try?{
          ??String?result?=?HttpClientUtil.doGet(url);
          ??System.out.println("請求結(jié)果:"?+?result);
          ??IdentityCheckResult?identityCheckResult?=?JsonUtils.parse(result,?IdentityCheckResult.class);
          ??IdentityCheck?identityCheck?=?JsonUtils.parse(result,?"result",?IdentityCheck.class);
          ??logger.info(identityCheckResult);
          ??logger.info(identityCheck.toString());
          ??if(identityCheckResult.correct()?&&?identityCheck.getRes()?==?1){
          ???match?=?true;
          ??}
          ?}?catch?(Exception?e)?{
          ??e.printStackTrace();
          ?}
          ?logger.info("<-----------------調(diào)用聚合數(shù)據(jù)?身份證驗證API?END---------------");
          ?return?match;
          }

          3、請求這個第三方接口:

          使用HttpClientUtil工具類中的doGet方法來請求URL,得到結(jié)果,現(xiàn)在大多數(shù)是一個json字符串,類型為String。

          4、根據(jù)接口返回數(shù)據(jù)格式來解析數(shù)據(jù):

          可以看到,返回參數(shù)有六個,所以在項目中新建一個bean,包含以上六個字段,用來接住返回數(shù)據(jù),如下:

          因為接口返回的數(shù)據(jù)是一個json的字符串,類型實際上是一個String字符串,要解析數(shù)據(jù),用工具類JsonUtils的parse方法將字符串轉(zhuǎn)換為Java對象,JsonUtils的代碼如下:

          package?com.eqianxian.commons.utils.json;
          ?
          import?java.util.List;
          import?java.util.Map;
          ?
          import?com.alibaba.fastjson.JSON;
          import?com.alibaba.fastjson.JSONObject;
          import?com.alibaba.fastjson.serializer.PropertyFilter;
          import?com.alibaba.fastjson.serializer.SerializerFeature;
          ?
          /**
          ?*?在系統(tǒng)中統(tǒng)一使用這個,以方便將來切換不同的JSON生成工具
          ?*?
          ?*?@author?KelvinZ
          ?*?
          ?*/
          public?class?JsonUtils?{
          ?public?static?final?int?TYPE_FASTJSON?=?0;
          ?public?static?final?int?TYPE_GSON?=?1;
          ?
          ?/**
          ??*?

          ??*?對象轉(zhuǎn)化為json字符串
          ??*?
          ??*?@param?obj?待轉(zhuǎn)化對象
          ??*?@return?代表該對象的Json字符串
          ??*/
          ?public?static?final?String?toJson(final?Object?obj)?{
          ??return?JSON.toJSONString(obj);
          ??//?return?gson.toJson(obj);
          ?}
          ?
          ?/**
          ??*?

          ??*?對象轉(zhuǎn)化為json字符串
          ??*?
          ??*?@param?obj?待轉(zhuǎn)化對象
          ??*?@return?代表該對象的Json字符串
          ??*/
          ?public?static?final?String?toJson(final?Object?obj,?SerializerFeature...?features)?{
          ??return?JSON.toJSONString(obj,?features);
          ??//?return?gson.toJson(obj);
          ?}
          ?
          ?/**
          ??*?對象轉(zhuǎn)化為json字符串并格式化
          ??*?
          ??*?@param?obj
          ??*?@param?format?是否要格式化
          ??*?@return
          ??*/
          ?public?static?final?String?toJson(final?Object?obj,?final?boolean?format)?{
          ??return?JSON.toJSONString(obj,?format);
          ?}
          ?
          ?/**
          ??*?對象對指定字段進(jìn)行過濾處理,生成json字符串
          ??*?
          ??*?@param?obj
          ??*?@param?fields?過濾處理字段
          ??*?@param?ignore?true做忽略處理,false做包含處理
          ??*?@param?features?json特征,為null忽略
          ??*?@return
          ??*/
          ?public?static?final?String?toJson(final?Object?obj,?final?String[]?fields,?final?boolean?ignore,
          ???SerializerFeature...?features)?{
          ??if?(fields?==?null?||?fields.length????return?toJson(obj);
          ??}
          ??if?(features?==?null)
          ???features?=?new?SerializerFeature[]?{?SerializerFeature.QuoteFieldNames?};
          ??return?JSON.toJSONString(obj,?new?PropertyFilter()?{
          ???@Override
          ???public?boolean?apply(Object?object,?String?name,?Object?value)?{
          ????for?(int?i?=?0;?i??????if?(name.equals(fields[i]))?{
          ??????return?!ignore;
          ?????}
          ????}
          ????return?ignore;
          ???}
          ??},?features);
          ?}
          ?
          ?/**
          ??*?

          ??*?解析json字符串中某路徑的值
          ??*?
          ??*?@param?json
          ??*?@param?path
          ??*?@return
          ??*/
          ?@SuppressWarnings("unchecked")
          ?public?static?final??E?parse(final?String?json,?final?String?path)?{
          ??String[]?keys?=?path.split(",");
          ??JSONObject?obj?=?JSON.parseObject(json);
          ??for?(int?i?=?0;?i????obj?=?obj.getJSONObject(keys[i]);
          ??}
          ??return?(E)?obj.get(keys[keys.length?-?1]);
          ?}
          ?
          ?/**
          ??*?

          ??*?json字符串解析為對象
          ??*?
          ??*?@param?json?代表一個對象的Json字符串
          ??*?@param?clazz?指定目標(biāo)對象的類型,即返回對象的類型
          ??*?@return?從json字符串解析出來的對象
          ??*/
          ?public?static?final??T?parse(final?String?json,?final?Class?clazz)?{
          ??return?JSON.parseObject(json,?clazz);
          ?}
          ?
          ?/**
          ??*?

          ??*?json字符串解析為對象
          ??*?
          ??*?@param?json?json字符串
          ??*?@param?path?逗號分隔的json層次結(jié)構(gòu)
          ??*?@param?clazz?目標(biāo)類
          ??*/
          ?public?static?final??T?parse(final?String?json,?final?String?path,?final?Class?clazz)?{
          ??String[]?keys?=?path.split(",");
          ??JSONObject?obj?=?JSON.parseObject(json);
          ??for?(int?i?=?0;?i????obj?=?obj.getJSONObject(keys[i]);
          ??}
          ??String?inner?=?obj.getString(keys[keys.length?-?1]);
          ??return?parse(inner,?clazz);
          ?}
          ?
          ?/**
          ??*?將制定的對象經(jīng)過字段過濾處理后,解析成為json集合
          ??*?
          ??*?@param?obj
          ??*?@param?fields
          ??*?@param?ignore
          ??*?@param?clazz
          ??*?@param?features
          ??*?@return
          ??*/
          ?public?static?final??List?parseArray(final?Object?obj,?final?String[]?fields,?boolean?ignore,
          ???final?Class?clazz,?final?SerializerFeature...?features)?{
          ??String?json?=?toJson(obj,?fields,?ignore,?features);
          ??return?parseArray(json,?clazz);
          ?}
          ?
          ?/**
          ??*?

          ??*?從json字符串中解析出一個對象的集合,被解析字符串要求是合法的集合類型
          ??*?(形如:["k1":"v1","k2":"v2",..."kn":"vn"])
          ??*?
          ??*?@param?json?-?[key-value-pair...]
          ??*?@param?clazz
          ??*?@return
          ??*/
          ?public?static?final??List?parseArray(final?String?json,?final?Class?clazz)?{
          ??return?JSON.parseArray(json,?clazz);
          ?}
          ?
          ?/**
          ??*?

          ??*?從json字符串中按照路徑尋找,并解析出一個對象的集合,例如:
          ??*?類Person有一個屬性name,要從以下json中解析出其集合:
          ??*?{
          ??*??"page_info":{
          ??*???"items":{
          ??*????"item":[{"name":"KelvinZ"},{"name":"Jobs"},...{"name":"Gates"}]
          ??*??}
          ??*?}
          ??*?使用方法:parseArray(json, "page_info,items,item",?Person.class),
          ??*?將根據(jù)指定路徑,正確的解析出所需集合,排除外層干擾
          ??*?
          ??*?@param?json?json字符串
          ??*?@param?path?逗號分隔的json層次結(jié)構(gòu)
          ??*?@param?clazz?目標(biāo)類
          ??*?@return
          ??*/
          ?public?static?final??List?parseArray(final?String?json,?final?String?path,?final?Class?clazz)?{
          ??String[]?keys?=?path.split(",");
          ??JSONObject?obj?=?JSON.parseObject(json);
          ??for?(int?i?=?0;?i????obj?=?obj.getJSONObject(keys[i]);
          ??}
          ??String?inner?=?obj.getString(keys[keys.length?-?1]);
          ??List?ret?=?parseArray(inner,?clazz);
          ??return?ret;
          ?}
          ?
          ?/**
          ??*?

          ??*?有些json的常見格式錯誤這里可以處理,以便給后續(xù)的方法處理
          ??*?常見錯誤:使用了\"?或者?"{?或者?}",騰訊的頁面中常見這種格式
          ??*?
          ??*?@param?invalidJson?包含非法格式的json字符串
          ??*?@return
          ??*/
          ?public?static?final?String?correctJson(final?String?invalidJson)?{
          ??String?content?=?invalidJson.replace("\\\"",?"\"").replace("\"{",?"{").replace("}\"",?"}");
          ??return?content;
          ?}
          ?
          ?/**
          ??*?格式化Json
          ??*?
          ??*?@param?json
          ??*?@return
          ??*/
          ?public?static?final?String?formatJson(String?json)?{
          ??Map?map?=?(Map)?JSON.parse(json);
          ??return?JSON.toJSONString(map,?true);
          ?}
          ?
          ?/**
          ??*?獲取json串中的子json
          ??*?
          ??*?@param?json
          ??*?@param?path
          ??*?@return
          ??*/
          ?public?static?final?String?getSubJson(String?json,?String?path)?{
          ??String[]?keys?=?path.split(",");
          ??JSONObject?obj?=?JSON.parseObject(json);
          ??for?(int?i?=?0;?i????obj?=?obj.getJSONObject(keys[i]);
          ???System.out.println(obj.toJSONString());
          ??}
          ??return?obj?!=?null???obj.getString(keys[keys.length?-?1])?:?null;
          ?}
          ?
          }

          來源:https://blog.csdn.net/qq_35860138/article/details/82967727

          ps:如果您覺文章有用,動動小手點個在看,點個再走吧

          -END-

          PS:如果覺得我的分享不錯,歡迎大家隨手點贊、在看。

          ?關(guān)注公眾號:Java后端編程,回復(fù)下面關(guān)鍵字?


          要Java學(xué)習(xí)完整路線,回復(fù)??路線?

          缺Java入門視頻,回復(fù)?視頻?

          要Java面試經(jīng)驗,回復(fù)??面試?

          缺Java項目,回復(fù):?項目?

          進(jìn)Java粉絲群:?加群?


          PS:如果覺得我的分享不錯,歡迎大家隨手點贊、在看。

          (完)




          加我"微信"?獲取一份 最新Java面試題資料

          請備注:666不然不通過~


          最近好文


          1、必須推薦的一個后臺管理系統(tǒng)

          2、無意中發(fā)現(xiàn)了一位清華妹子的資料庫!

          3、Java后端編程讀者群正式成立了!

          4、一套簡單通用的Java后臺管理系統(tǒng),拿來即用

          5、36 張圖梳理 Intellij IDEA 常用設(shè)置



          最近面試BAT,整理一份面試資料Java面試BAT通關(guān)手冊,覆蓋了Java核心技術(shù)、JVM、Java并發(fā)、SSM、微服務(wù)、數(shù)據(jù)庫、數(shù)據(jù)結(jié)構(gòu)等等。
          獲取方式:關(guān)注公眾號并回復(fù)?java?領(lǐng)取,更多內(nèi)容陸續(xù)奉上。
          明天見(??ω??)??
          瀏覽 70
          點贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  91久久在线 | 欧美大鸡吧视频 | 日韩十八禁 | 操逼网大香蕉 | 国产成人精品免费视频麻豆大全 |