目录
1.背景
最近做了一个项目,需要实现直播的功能,而且目前已经有了一台示教主机,示教主机上面接上摄像头,远程登陆示教主机服务器绑定直播地址(腾讯直播等)即可。本片文章在这样的背景下介绍一下如何与其他服务器进行数据传输。
2.通过HttpURLConnection访问其他服务器
网上资料有很多具体如下:
- 该博客重点介绍了:HttpURLConnection与HttpClient浅析
- 该博客重点介绍了ajax跨域问题(三种解决方案)https://blog.csdn.net/u014727260/article/details/72793459
本人使用的是HttpURLConnection来访问示教主机,示教主机是一个linux的服务器,数据的传输格式为XML,双方严格按照cgi接口文档进行相关功能的调用与数据传输。linux服务器中的逻辑代码可以是c++等其它语言,满足cgi协议即可。
接口文档的形式如下:
<!--功能:获取可用状态的用户名列表-->
<!--URL:/xxxcgi/xxx/GetUserList-->
<!--所需权限: xxx, xxx-->
<!--Request:none-->
<!--Response:-->
<GetUserListResp>
<UserList num="1">
<User></User> <!--xs:string 可用的用户名-->
</UserList>
</GetUserListResp>
由于发送返回的数据格式皆为xml,所以需要解析,现给出相关功能调用工具,提醒,包名需自己补齐。
- HttpURLConnection工具包
package com.xxxxxxxxxx.util;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpConnectUtil {
/**
* 与服务器建立连接
* @param reqUrl
* @param reqMethod
* @return map
* @throws Exception
*/
public static Map<String, String> ManageConnection(String reqUrl, String reqMethod , String messageXML) throws Exception {
System.out.println(messageXML);
URL url;
String xml =messageXML;
byte[] data = xml.getBytes("UTF-8");//得到了xml的实体数据
url = new URL(reqUrl);
MessageUtil messageUtil =new MessageUtil();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(20* 1000);
con.setReadTimeout(20* 1000);
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "application/xml");
con.setRequestProperty("Content-Length", String.valueOf(data.length));
con.setRequestProperty("Charset", "UTF-8");
if (null != reqMethod && !reqMethod.equals("")) {
con.setRequestMethod(reqMethod);
} else {
con.setRequestMethod("GET");
}
//发送消息
if (!messageXML.isEmpty())
{
OutputStream outStream = con.getOutputStream();//消息不为空,会自动连接,否则加上con.connect();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println("消息已经发送");
}
System.out.println("con.getResponseCode()"+con.getResponseCode());
//接受消息
if (con.getResponseCode() == 200) {
InputStream responseStream = con.getInputStream();
System.out.println("消息获取到了");
return messageUtil.parseXml(responseStream);
}
else
{
InputStream responseStream = con.getErrorStream();
System.out.println("wrong消息获取到了");
return messageUtil.parseXml(responseStream);
}
}
}
- 使用SAXReader解析xml
package com.xxxxxxxx.util; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.*; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class MessageUtil { public static Map<String, String> xmlmap = new HashMap<String,String>(); //存储xml元素信息的容器 private static List<String> elemList = new ArrayList<String>(); public static List<String> getElemList() { return elemList; } public static void setElemList(List<String> elemList) { MessageUtil.elemList = elemList; } /** * 解析服务器发来的请求(XML) * * @param responseStream * @return map * @throws Exception */ public Map<String, String> parseXml(InputStream responseStream) throws Exception { // 将解析结果清理一下 xmlmap.clear(); elemList.clear(); // 从request中取得输入流 InputStream inputStream = responseStream; System.out.println("获取输入流"); // printXml(inputStream); String a = null; byte[] data1 = new byte[inputStream.available()]; inputStream.read(data1); // 转成字符串 a = new String(data1); System.out.println(a); // 读取输入流 SAXReader reader = new SAXReader(); Document document = reader.read(new ByteArrayInputStream(a.getBytes("utf-8"))); // 得到xml根元素 Element root = document.getRootElement(); xmlmap.put("root",root.getName()); //判断responsestatus // 得到根元素的所有子节点 getElementList(root); String x = getListString(elemList); System.out.println("-----------elemList解析结果------------"); System.out.println(x); /* System.out.println("-----------xmlmap解析结果------------"); System.out.println(xmlmap);*/ // 释放资源 inputStream.close(); inputStream = null; return xmlmap; } /** * 递归遍历方法 * * @param element */ public void getElementList(Element element) { List elements = element.elements(); if (elements.size() == 0) { //没有子元素 String xpath = element.getPath(); //根节点内文本 String value = element.getTextTrim(); elemList.add(xpath + " " + value); } else { //有子元素 // 使用方法iterator()要求容器返回一个Iterator,elements实质上是一个list for (Iterator it = elements.iterator(); it.hasNext(); ) { //第一次调用Iterator的next()方法时,它返回序列的第一个元素 Element elem = (Element) it.next(); //递归遍历|相同key值的value存储一起 if (xmlmap.containsKey(elem.getName())){ String oldValue =xmlmap.get(elem.getName()); xmlmap.put(elem.getName(), oldValue+"|"+elem.getText()); } else { xmlmap.put(elem.getName(), elem.getText());} //自己把自己当做根节点递归 getElementList(elem); } } } public String getListString(List<String> elemList) { StringBuffer sb = new StringBuffer(); for (Iterator<String> it = elemList.iterator(); it.hasNext(); ) { String str = it.next(); sb.append(str + "\n"); } return sb.toString(); } private void printXml(InputStream in) throws Exception { String a = null; byte[] data1 = new byte[in.available()]; in.read(data1); // 转成字符串 a = new String(data1); System.out.println(a); } }