Java如何遠程調(diào)用對方接口
Java遠程調(diào)用對方接口
在實際的項目開發(fā)中,經(jīng)常需要調(diào)用遠程接口,那java是如何實現(xiàn)調(diào)用遠程接口的呢?這里主要介紹java調(diào)用遠程接口的兩種方式:
一、調(diào)用遠程http接口
通過jdk的網(wǎng)絡類Java.net.HttpURLConnection調(diào)用第三方http接口
/**
* @Auther kezf
* @Date 2020/4/11
* @param urlStr 目標地址
* @param json 請求參數(shù)
* @param charset 編碼
* @return
*/
public static String doPost(String urlStr,String json,String charset) {
String result = null;
System.out.println("請求參數(shù):"+json);
try {
//獲取目標地址
URL url = new URL(urlStr);
//創(chuàng)建連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設置向HttpURLConnection輸出、輸入(發(fā)送數(shù)據(jù)、接收數(shù)據(jù)),當請求為post時必須設置這兩個參數(shù)
connection.setDoOutput(true);
connection.setDoInput(true);
//設置請求方式
connection.setRequestMethod("POST");
//設置是否開啟緩存,post請求時,緩存必須關掉
connection.setUseCaches(false);
//設置連接是否自動處理重定向(setFollowRedirects:所用http連接;setInstanceFollowRedirects:本次連接)
connection.setInstanceFollowRedirects(true);
//設置提交內(nèi)容類型
connection.setRequestProperty("Content-Type","application/json");
//開始連接
connection.connect();
//發(fā)送請求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(json.getBytes(charset));
out.flush();
out.close();
//讀取響應
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("請求返回結果:"+result);
reader.close();
// 斷開連接
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)用遠程Web Service 接口
使用axis的call方式調(diào)用
public String signConfirm(TpgDsfxyxx dsfxyqdxx){
String result=null;
try {
//創(chuàng)建服務
Service service = new Service();
//創(chuàng)建Call對象
Call call = (Call) service.createCall();
//設置服務所在的地址
call.setTargetEndpointAddress(StringUtil.getGzfconfigValueByName("dsfxy_qd_url"));
//設置調(diào)用方法名
call.setOperation("SignConfirm");
//添加請求參數(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)用服務
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ū)別
常見的API接口有兩類:http接口和webservice接口。
- http接口走http協(xié)議,通過路徑來區(qū)分調(diào)用方法,請求報文一般是key-value形式的,返回報文一般是json串,常用的是get和post方法來請求。
- webservice接口走的soap協(xié)議,通過http傳輸,請求報文和返回報文都是xml格式的
封裝一個java調(diào)用遠程接口工具類
java調(diào)用遠程接口的工具類
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 {
//遠程調(diào)用接口
/**
*
* @param url:遠程接口url
* @param timeout:連接超時時間
* @param object:如所需參數(shù)是json對象類型,先將參數(shù)封裝成JSONObject類型
* @param method:發(fā)送方式:以post還是get
* @param contentType:指定HTTP的Content-Type類型
* @return 返回的是接口返回內(nèi)容對應的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();
}
}
適用場景
開發(fā)過程中離不開直接通過后端訪問某些接口來拿數(shù)據(jù),比如需要和另外的平臺進行數(shù)據(jù)的交互或者對接
我們就會去參考對方給的接口文檔進行數(shù)據(jù)訪問,這時就可以使用這個工具類,相對還是比較方便的
使用方法簡述
- 接口傳參方式
接口所需的是普通鍵值對:直接跟在url后面進行傳參,obj參數(shù)傳一個空的JSONObject對象,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對象里面,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方式訪問請求,這里要求大寫,傳字符串"POST"或者"GET";contentType參數(shù)用來指定http對應的Content-Type內(nèi)容,一般對應的接口文檔會給出,這里我們也需要進行明確指定。
順便聊一聊另一個參數(shù)JSONObject,可以很好的用來進行對象和json字符串的轉換,通過導的包可以看出,使用的是阿里的;因為使用阿里的效率更高,運行速度更快;而且JSONObject這部分內(nèi)容低版本有漏洞,所以需要使用盡可能高的版本。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用java實現(xiàn)備份和恢復SQLServer表數(shù)據(jù)
這篇文章主要為大家詳細介紹了如何使用java實現(xiàn)備份和恢復SQLServer表數(shù)據(jù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-01-01
@Transactional遇到try catch失效的問題
這篇文章主要介紹了@Transactional遇到try catch失效的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
解決springboot 多線程使用MultipartFile讀取excel文件內(nèi)容報錯問題
這篇文章主要介紹了解決springboot 多線程使用MultipartFile讀取excel文件內(nèi)容報錯問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
微信小程序與AspNetCore SignalR聊天實例代碼
這篇文章主要介紹了微信小程序與AspNetCore SignalR聊天實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
Java實戰(zhàn)之吃貨聯(lián)盟訂餐系統(tǒng)
這篇文章主要介紹了Java實戰(zhàn)之吃貨聯(lián)盟訂餐系統(tǒng),文中有非常詳細的代碼示例,對正在學習java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
如何動態(tài)改變Retrofit的base url和rest版本詳解
這篇文章主要給大家介紹了關于如何動態(tài)改變Retrofit的base url和rest版本的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-09-09

