在平常的项目开发中,经常会遇到多系统、跨平台的接口调用,常用的接口调用方式有RMI、HTML、WebService、Socket、JMS等,本文将详细介绍HTML接口的调用方式。
1、读取URL的内容
public String getMessage(String urlValue){
StringBuffer result = new StringBuffer();
try {
URL url = new URL(urlValue);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
con.connect();
System.out.println("HTTP状态码="+con.getResponseCode());
BufferedReader inn = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String value = inn.readLine().trim();
while(value != null){
if(!"".equals(value)){
result.append(value.trim()+"\n");
}
value = inn.readLine();
}
inn.close();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
如果参数urlValue的值为
http://www.baidu.com
则返回以下内容(由于内容太多,这里只呈现一部分)
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel=&