最近有个需求需要接⼊xml格式的接⼝,踩坑多次。记录⼀下发送请求附带Authorization请求头,请求头⽣成代码:
public static String doPost(String urlStr, String xml) {
byte[] xmlData = Bytes();
DataInputStream input = null;
java.io.ByteArrayOutputStream out = null;
try {
//获得到位置服务的链接
URL url = new URL(urlStr);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);使用dom4j解析xml文件
urlCon.setUseCaches(false);
//将xml数据发送到位置服务
urlCon.setRequestProperty("Content-Type", "text/xml");
urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
//加⼊请求头
urlCon.setRequestProperty("Authorization", getHeader());
DataOutputStream printout = new OutputStream());
printout.write(xmlData);
printout.flush();
printout.close();
input = new InputStream());
out = new java.io.ByteArrayOutputStream();
byte[] bufferByte = new byte[256];
int l = -1;
int downloadSize = 0;
while ((l = ad(bufferByte)) > -1) {
downloadSize += l;
out.write(bufferByte, 0, l);
out.flush();
}
String();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
input.close();
} catch (Exception ex) {
}
}
String();
}
返回后的String为xml⽂本,对xml格式不熟悉,所以写了个xml转成json格式的⼯具,还是json好⽤呀。xml转Json⼯具需要的pom如下:
<!-- mvnrepository/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<!-- mvnrepository/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
xml转Json⼯具代码如下:
/**
* xml转json
*
* @param element
* @param json
*/
public static void dom4j2Json(Element element, JSONObject json) {        //如果是属性
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!Value().isEmpty()) {
json.put("@" + Name(), Value());
}
}
List<Element> chdEl = element.elements();
if (chdEl.isEmpty() && !Text().isEmpty()) {
//如果没有⼦元素,只有⼀个值
json.Name(), Text());
}
for (Element e : chdEl) {
//有⼦元素
if (!e.elements().isEmpty()) {
//⼦元素也有⼦元素
JSONObject chdjson = new JSONObject();
dom4j2Json(e, chdjson);
Object o = (e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {
//如果此元素已存在,则转为jsonArray
JSONObject jsono = (JSONObject) o;
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.Name(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.Name(), chdjson);
}
}
} else {
//⼦元素没有⼦元素
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!Value().isEmpty()) {
json.put("@" + Name(), Value());
}
}
if (!e.getText().isEmpty()) {
json.Name(), e.getText());
}
}
}
}
测试转换⼯具代码如下:
public static List<Empl> test(String sb) throws Exception {        //sb是xml的String
Document doc = DocumentHelper.parseText(sb);
JSONObject json = new JSONObject();
RootElement(), json);
String body= String("Body")

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。