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>
  1. 报文示例
<STUDENT> 
     <AGE>18</AGE>
     <NAME>
         <XING></XING>
         <MING>明玉</MING>
     </NAME>
     <NAME>
     	 <XING></XING>
         <MING>明德</MING>
     </NAME>
</STUDENT>
  1. 报文拼接
 StringBuffer strBuff = new StringBuffer();
 
 strBuff.append("");
 strBuff.append("18");
 strBuff.append("");
 strBuff.append("");
 strBuff.append("明玉");
 strBuff.append("");
 strBuff.append("");
 strBuff.append("");
 strBuff.append("明德");
 strBuff.append("");
 strBuff.append("");
 
 String xmlStr = strBuff.toString;
  1. 报文发送,post请求接口调用,xmlStr为xml格式请求参数体
 public String postXml(String xmlStr){
 
 	  //可改变请求参数体编码GBK/UTF-8
      RequestBody body= RequestBody.create(MediaType.parse("application/xml;charset=GBK"), xmlStr);
      //url为接口地址
      Request requestOk = new Request.Builder().url("http://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 = client.newCall(requestOk).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
      //获取响应 
	  String jsonString = response.body().string();
      return jsonString;
  }
  1. 报文解析,进行实体解析
 //STUDENT为XML最大节点
 JAXBContext context = JAXBContext.newInstance(STUDENT.class);
 Unmarshaller unmarshaller = context.createUnmarshaller();
 
 //jsonString为报文响应
 STUDENT student = (STUDENT)unmarshaller.unmarshal(new StringReader(jsonString));
  1. 实体类
//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 +
                '}';
    }
}

你可能感兴趣的:(http,xml,post,网络)