场景类比
高级开发:给你一个url,然后把这些数据添加到咱们数据库里;
新手:“*?.#¥..”什么鬼,这明明只是一个url啊,哪有数据呀?
使用原因
从另一个平台的数据想要在本系统使用,这里就涉及到了我们需要调用别人的接口;其中,调用别人的接口据我所知道的,可能有2种(如有不对,欢迎大家指正):
- http请求;
- tcp请求
主要看接口文档是哪一个;当然,在处理tcp请求的时候会比较复杂。在这里,我们主要讲的是http请求;
如果此篇不是你所需要的,那么你可能是遇到这种情况:调用接口数据遭遇拦截,需登录?如何跳过登录?
参数说明:
-
URL url = new URL(path); // 接口地址 注意,此处URL类是java.net.*下的类
-
打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
设置通用的请求属性
conn.setRequestProperty("accept", "/");
...
我来讲一下这块是干嘛的,在这里通过你设置的请求参数,返回一些你可以指定的内容,比如cookie欺骗就是在这里设置的,通过客户端获取的cookie值,然后作为请求值,就可以获取相应的内容,然后这些参数都是可以设置的
-
设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setDoOutput(true);
conn.setDoInput(true);
-
断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
http请求调用接口代码:
public static String interfaceUtil(String path,String data) {
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(path);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//请求方式
//conn.setRequestMethod("POST");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//设置是否向httpUrlConnection输出,发送post请求必须设置这两个
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数即数据
out.print(data);
//缓冲数据
out.flush();
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
//关闭流
is.close();
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
测试类:
public static void main(String[] args){
String data = ToInterface.interfaceUtil(requestPath,"");
System.out.println(data);
/**
说明:
1. 如果是get请求,格式为:
path = http://www.xxx:xx/xx/xx/xx?userName=zhangsan&password=1111
ToInterface.interfaceUtil(requestPath,"");
2. 如果是post请求,格式为:http://www.xxx:xx/xx/xx/xx
ToInterface.interfaceUtil(requestPath,"userName=zhangsan&password=111");
*/
}