java中xml进⾏报⽂发送和解析1. 利⽤OKhttp⽹络框架,进⾏Maven项⽬管理
//报⽂发送
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.8.0</version>
</dependency>
//报⽂解析
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
</dependency>
2. 报⽂⽰例
<STUDENT>
<AGE>18</AGE>
<NAME>
<XING>赵</XING>
<MING>明⽟</MING>
</NAME>
<NAME>
<XING>沙</XING>
<MING>明德</MING>
</NAME>
</STUDENT>
3. 报⽂拼接
StringBuffer strBuff =new StringBuffer();
strBuff.append("<STUDENT>");
strBuff.append("<AGE>18</AGE>");
strBuff.append("<NAME>");
strBuff.append("<XING>赵</XING>");
strBuff.append("<MING>明⽟</MING>");
strBuff.append("</NAME>");
strBuff.append("<NAME>");
strBuff.append("<XING>沙</XING>");
strBuff.append("<MING>明德</MING>");
strBuff.append("</NAME>");
strBuff.append("</STUDENT>");
String xmlStr = String;
4. 报⽂发送,post请求接⼝调⽤,xmlStr为xml格式请求参数体
public String postXml(String xmlStr){
//可改变请求参数体编码GBK/UTF-8
RequestBody body= ate(MediaType.parse("application/xml;charset=GBK"), xmlStr);
//url为接⼝地址java xml是什么
Request requestOk =new Request.Builder().url("192.168.0.103:8007").post(body).build();
//⽹络请求
OkHttpClient client =new OkHttpClient.Builder().retryOnConnectionFailure(true).build();
//可⼿动设置连接时长
OkHttpClient client =new OkHttpClient().newBuilder().connectTimeout(60000, TimeUnit.MILLISECONDS) .readTimeout(60000, TimeUnit.MILLISECONDS)
.build();
//获取处理结果
Response response = null;
try{
response = wCall(requestOk).execute();
}catch(IOException e){
e.printStackTrace();
}
//获取响应
String jsonString = response.body().string();
return jsonString;
}
5. 报⽂解析,进⾏实体解析
//STUDENT为XML最⼤节点
JAXBContext context = wInstance(STUDENT.class);
Unmarshaller unmarshaller = ateUnmarshaller();
//jsonString为报⽂响应
STUDENT student =(STUDENT)unmarshaller.unmarshal(new StringReader(jsonString));
6. 实体类
//XmlRootElement注解是将类与XML元素进⾏映射,XML节点与属性⼤⼩写保持⼀致
@XmlRootElement(name ="STUDENT")
public class STUDENT implements Serializable {
private String AGE;
private List<NAME> NAME;
public String getAGE(){
return AGE;
}
public void setAGE(String AGE){
this.AGE = AGE;
}
public List<NAME>getNAME(){
return NAME;
}
public void setNAME(List<NAME> NAME){
this.NAME = NAME;
}
@Override
public String toString(){
return"Cccc{"+
"AGE='"+ AGE +'\''+
", NAME="+ NAME +
'}';
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论