Java如何遠(yuǎn)程調(diào)用對(duì)方接口
Java遠(yuǎn)程調(diào)用對(duì)方接口
在實(shí)際的項(xiàng)目開(kāi)發(fā)中,經(jīng)常需要調(diào)用遠(yuǎn)程接口,那java是如何實(shí)現(xiàn)調(diào)用遠(yuǎn)程接口的呢?這里主要介紹java調(diào)用遠(yuǎn)程接口的兩種方式:
一、調(diào)用遠(yuǎn)程http接口
通過(guò)jdk的網(wǎng)絡(luò)類(lèi)Java.net.HttpURLConnection調(diào)用第三方http接口
/**
* @Auther kezf
* @Date 2020/4/11
* @param urlStr 目標(biāo)地址
* @param json 請(qǐng)求參數(shù)
* @param charset 編碼
* @return
*/
public static String doPost(String urlStr,String json,String charset) {
String result = null;
System.out.println("請(qǐng)求參數(shù):"+json);
try {
//獲取目標(biāo)地址
URL url = new URL(urlStr);
//創(chuàng)建連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設(shè)置向HttpURLConnection輸出、輸入(發(fā)送數(shù)據(jù)、接收數(shù)據(jù)),當(dāng)請(qǐng)求為post時(shí)必須設(shè)置這兩個(gè)參數(shù)
connection.setDoOutput(true);
connection.setDoInput(true);
//設(shè)置請(qǐng)求方式
connection.setRequestMethod("POST");
//設(shè)置是否開(kāi)啟緩存,post請(qǐng)求時(shí),緩存必須關(guān)掉
connection.setUseCaches(false);
//設(shè)置連接是否自動(dòng)處理重定向(setFollowRedirects:所用http連接;setInstanceFollowRedirects:本次連接)
connection.setInstanceFollowRedirects(true);
//設(shè)置提交內(nèi)容類(lèi)型
connection.setRequestProperty("Content-Type","application/json");
//開(kāi)始連接
connection.connect();
//發(fā)送請(qǐng)求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(json.getBytes(charset));
out.flush();
out.close();
//讀取響應(yīng)
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes());
sb.append(lines);
}
result = sb.toString();
System.out.println("請(qǐng)求返回結(jié)果:"+result);
reader.close();
// 斷開(kāi)連接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
二、調(diào)用遠(yuǎn)程Web Service 接口
使用axis的call方式調(diào)用
public String signConfirm(TpgDsfxyxx dsfxyqdxx){
String result=null;
try {
//創(chuàng)建服務(wù)
Service service = new Service();
//創(chuàng)建Call對(duì)象
Call call = (Call) service.createCall();
//設(shè)置服務(wù)所在的地址
call.setTargetEndpointAddress(StringUtil.getGzfconfigValueByName("dsfxy_qd_url"));
//設(shè)置調(diào)用方法名
call.setOperation("SignConfirm");
//添加請(qǐng)求參數(shù)
call.addParameter("xyh", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("sqh", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("yzm", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("sfywzl", XMLType.XSD_INTEGER, ParameterMode.IN);
call.addParameter("jldxhh", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("jldxhm", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("zjlx", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("zjhm", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("dhhm", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("dz", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("fkryhdm", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("fkrkhh", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("fkrzh", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("fkrmc", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("fkrlx", XMLType.XSD_INTEGER, ParameterMode.IN);
call.setReturnType(XMLType.XSD_STRING);
System.out.println(dsfxyqdxx.toString());
//調(diào)用服務(wù)
result = (String) call.invoke(new Object[]{String.valueOf(dsfxyqdxx.getId()), dsfxyqdxx.getSqh(), dsfxyqdxx.getYzm(),
dsfxyqdxx.getSfywzl(), dsfxyqdxx.getJldxhh(), dsfxyqdxx.getJldxhm(), dsfxyqdxx.getZjlx(),
dsfxyqdxx.getZjhm(), dsfxyqdxx.getDhhm(), dsfxyqdxx.getDz(), dsfxyqdxx.getFkryhdm(),
dsfxyqdxx.getFkrkhh(), dsfxyqdxx.getFkrzh(), dsfxyqdxx.getFkrmc(), dsfxyqdxx.getFkrlx()});
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("signConfirm###:" + result);
return result;
}
三、http接口和web service 接口的區(qū)別
常見(jiàn)的API接口有兩類(lèi):http接口和webservice接口。
- http接口走h(yuǎn)ttp協(xié)議,通過(guò)路徑來(lái)區(qū)分調(diào)用方法,請(qǐng)求報(bào)文一般是key-value形式的,返回報(bào)文一般是json串,常用的是get和post方法來(lái)請(qǐng)求。
- webservice接口走的soap協(xié)議,通過(guò)http傳輸,請(qǐng)求報(bào)文和返回報(bào)文都是xml格式的
封裝一個(gè)java調(diào)用遠(yuǎn)程接口工具類(lèi)
java調(diào)用遠(yuǎn)程接口的工具類(lèi)
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
public class RemoteDemo {
//遠(yuǎn)程調(diào)用接口
/**
*
* @param url:遠(yuǎn)程接口url
* @param timeout:連接超時(shí)時(shí)間
* @param object:如所需參數(shù)是json對(duì)象類(lèi)型,先將參數(shù)封裝成JSONObject類(lèi)型
* @param method:發(fā)送方式:以post還是get
* @param contentType:指定HTTP的Content-Type類(lèi)型
* @return 返回的是接口返回內(nèi)容對(duì)應(yīng)的json字符串
*/
public static String remoteJsonRequest(String url, int timeout, JSONObject object, String method, String contentType) {
URL connect;
StringBuffer data = new StringBuffer();
try {
connect = new URL(url);
HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.setReadTimeout(timeout);
connection.setRequestProperty("Content-Type", contentType);
OutputStreamWriter paramout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
paramout.write(object.toString());
paramout.flush();
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
String line;
while ((line = reader.readLine()) != null) {
data.append(line);
}
paramout.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return data.toString();
}
}
適用場(chǎng)景
開(kāi)發(fā)過(guò)程中離不開(kāi)直接通過(guò)后端訪問(wèn)某些接口來(lái)拿數(shù)據(jù),比如需要和另外的平臺(tái)進(jìn)行數(shù)據(jù)的交互或者對(duì)接
我們就會(huì)去參考對(duì)方給的接口文檔進(jìn)行數(shù)據(jù)訪問(wèn),這時(shí)就可以使用這個(gè)工具類(lèi),相對(duì)還是比較方便的
使用方法簡(jiǎn)述
- 接口傳參方式
接口所需的是普通鍵值對(duì):直接跟在url后面進(jìn)行傳參,obj參數(shù)傳一個(gè)空的JSONObject對(duì)象,Demo如下:
JSONObject obj = new JSONObject();
RemoteDemo.remoteJsonRequest("http://localhost:8080/xx/xx?k1=v1&k2=v2", 5000, obj, "POST" ,"application/x-www-form-urlencoded");
接口所需的是json字符串:則將參數(shù)封裝在JSONObject對(duì)象里面,Demo如下:
JSONObject obj = new JSONObject();
obj.put("k1", "v1");
obj.put("k2", "v2");
RemoteDemo.remoteJsonRequest("http://localhost:8080/xx/xx", 5000, obj, "POST", "application/json");
另外就是參數(shù)method和參數(shù)contentType,method是指定以post方式還是get方式訪問(wèn)請(qǐng)求,這里要求大寫(xiě),傳字符串"POST"或者"GET";contentType參數(shù)用來(lái)指定http對(duì)應(yīng)的Content-Type內(nèi)容,一般對(duì)應(yīng)的接口文檔會(huì)給出,這里我們也需要進(jìn)行明確指定。
順便聊一聊另一個(gè)參數(shù)JSONObject,可以很好的用來(lái)進(jìn)行對(duì)象和json字符串的轉(zhuǎn)換,通過(guò)導(dǎo)的包可以看出,使用的是阿里的;因?yàn)槭褂冒⒗锏男矢?,運(yùn)行速度更快;而且JSONObject這部分內(nèi)容低版本有漏洞,所以需要使用盡可能高的版本。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
新版本Spring中l(wèi)ombok失效的問(wèn)題解決
Lombok是一個(gè)Java庫(kù),通過(guò)添加注解簡(jiǎn)化代碼編寫(xiě),本文主要介紹了新版本Spring中l(wèi)ombok失效的問(wèn)題解決,感興趣的可以了解一下2025-01-01
使用java實(shí)現(xiàn)備份和恢復(fù)SQLServer表數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了如何使用java實(shí)現(xiàn)備份和恢復(fù)SQLServer表數(shù)據(jù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01
@Transactional遇到try catch失效的問(wèn)題
這篇文章主要介紹了@Transactional遇到try catch失效的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
一文秒懂通過(guò)JavaCSV類(lèi)庫(kù)讀寫(xiě)CSV文件的技巧
本文給大家推薦第三方工具庫(kù) JavaCSV,用來(lái)造一些 csv 測(cè)試數(shù)據(jù)文件,使用超級(jí)方便,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2021-05-05
Java 中synchronize函數(shù)的實(shí)例詳解
這篇文章主要介紹了Java 中synchronize函數(shù)的實(shí)例詳解的相關(guān)資料,希望通過(guò)本文能幫助到大家理解使用synchronize函數(shù)的使用方法,需要的朋友可以參考下2017-09-09
解決springboot 多線程使用MultipartFile讀取excel文件內(nèi)容報(bào)錯(cuò)問(wèn)題
這篇文章主要介紹了解決springboot 多線程使用MultipartFile讀取excel文件內(nèi)容報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
微信小程序與AspNetCore SignalR聊天實(shí)例代碼
這篇文章主要介紹了微信小程序與AspNetCore SignalR聊天實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08
Java實(shí)戰(zhàn)之吃貨聯(lián)盟訂餐系統(tǒng)
這篇文章主要介紹了Java實(shí)戰(zhàn)之吃貨聯(lián)盟訂餐系統(tǒng),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
如何動(dòng)態(tài)改變Retrofit的base url和rest版本詳解
這篇文章主要給大家介紹了關(guān)于如何動(dòng)態(tài)改變Retrofit的base url和rest版本的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09

