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这部分内容低版本有漏洞,所以需要使用尽可能高的版本。