Java远程调用对方接口
在实际的项目开发中,经常需要调用远程接口,那java是如何实现调用远程接口的呢?这里主要介绍java调用远程接口的两种方式:
一、调用远程http接口
通过jdk的网络类Java.net.HttpURLConnection调用第三方http接口
/**
* @Auther kezf
* @Date 2020/4/11
* @param urlStr 目标地址
* @param json 请求参数
* @param charset 编码
* @return
*/
public static String doPost(String urlStr,String json,String charset) {
String result = null;
System.out.println("请求参数:"+json);
try {
//获取目标地址
URL url = new URL(urlStr);
//创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置向HttpURLConnection输出、输入(发送数据、接收数据),当请求为post时必须设置这两个参数
connection.setDoOutput(true);
connection.setDoInput(true);
//设置请求方式
connection.setRequestMethod("POST");
//设置是否开启缓存,post请求时,缓存必须关掉
connection.setUseCaches(false);
//设置连接是否自动处理重定向(setFollowRedirects:所用http连接;setInstanceFollowRedirects:本次连接)
connection.setInstanceFollowRedirects(true);
//设置提交内容类型
connection.setRequestProperty("Content-Type","application/json");
//开始连接
connection.connect();
//发送请求
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;
}
二、调用远程Web Service 接口
使用axis的call方式调用
public String signConfirm(TpgDsfxyxx dsfxyqdxx){
String result=null;
try {
//创建服务
Service service = new Service();
//创建Call对象
Call call = (Call) service.createCall();
//设置服务所在的地址
call.setTargetEndpointAddress(StringUtil.getGzfconfigValueByName("dsfxy_qd_url"));
//设置调用方法名
call.setOperation("SignConfirm");
//添加请求参数
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());
//调用服务
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 接口的区别
常见的API接口有两类:http接口和webservice接口。
- http接口走http协议,通过路径来区分调用方法,请求报文一般是key-value形式的,返回报文一般是json串,常用的是get和post方法来请求。
- webservice接口走的soap协议,通过http传输,请求报文和返回报文都是xml格式的
封装一个java调用远程接口工具类
java调用远程接口的工具类
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 {
//远程调用接口
/**
*
* @param url:远程接口url
* @param timeout:连接超时时间
* @param object:如所需参数是json对象类型,先将参数封装成JSONObject类型
* @param method:发送方式:以post还是get
* @param contentType:指定HTTP的Content-Type类型
* @return 返回的是接口返回内容对应的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();
}
}
适用场景
开发过程中离不开直接通过后端访问某些接口来拿数据,比如需要和另外的平台进行数据的交互或者对接
我们就会去参考对方给的接口文档进行数据访问,这时就可以使用这个工具类,相对还是比较方便的
使用方法简述
- 接口传参方式
接口所需的是普通键值对:直接跟在url后面进行传参,obj参数传一个空的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字符串:则将参数封装在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");
另外就是参数method和参数contentType,method是指定以post方式还是get方式访问请求,这里要求大写,传字符串"POST"或者"GET";contentType参数用来指定http对应的Content-Type内容,一般对应的接口文档会给出,这里我们也需要进行明确指定。
顺便聊一聊另一个参数JSONObject,可以很好的用来进行对象和json字符串的转换,通过导的包可以看出,使用的是阿里的;因为使用阿里的效率更高,运行速度更快;而且JSONObject这部分内容低版本有漏洞,所以需要使用尽可能高的版本。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

