欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 中HttpClient传输xml字符串实例详解

程序员文章站 2024-03-01 12:46:40
java 中httpclient传输xml字符串实例详解 介绍:我现在有一个对象page,需要将page对象转换为xml格式并以binary方式传输到服务端 其中涉...

java 中httpclient传输xml字符串实例详解

介绍:我现在有一个对象page,需要将page对象转换为xml格式并以binary方式传输到服务端

其中涉及到的技术点有:

1、对象转xml流
2、输出流转输入流
3、httpclient发送二进制流数据

pom文件依赖配置

<dependencies> 
  <dependency> 
    <groupid>junit</groupid> 
    <artifactid>junit</artifactid> 
    <version>3.8.1</version> 
    <scope>test</scope> 
  </dependency> 
  <dependency> 
    <groupid>org.apache.httpcomponents</groupid> 
    <artifactid>httpclient</artifactid> 
    <version>4.5.2</version> 
  </dependency> 
   
  <dependency> 
   <groupid>org.apache.httpcomponents</groupid> 
   <artifactid>httpmime</artifactid> 
   <version>4.5.2</version> 
  </dependency> 
  <dependency> 
    <groupid>commons-lang</groupid> 
    <artifactid>commons-lang</artifactid> 
    <version>2.4</version> 
  </dependency> 
  <dependency> 
    <groupid>com.google.code.gson</groupid> 
    <artifactid>gson</artifactid> 
    <version>2.2.4</version> 
    <type>jar</type> 
    <scope>compile</scope> 
  </dependency> 
  <dependency> 
    <groupid>org.xwiki.platform</groupid> 
    <artifactid>xwiki-platform-rest-model</artifactid> 
    <version>7.2</version> 
  </dependency> 
</dependencies> 

java代码示例

public void testnewpage() throws exception{ 
    //定义对象 
    page page =new page(); 
    page.settitle("testpage"); 
    page.setsyntax("xwiki/2.0"); 
    page.setcontent("this is a testpage"); 
    page.setid("xwiki:main.testpage"); 
    //初始化并转换对象为xml文件的流 
    jaxbcontext context = jaxbcontext.newinstance("org.xwiki.rest.model.jaxb"); 
    marshaller marshaller=context.createmarshaller(); 
    unmarshaller unmarshaller = context.createunmarshaller(); 
    bytearrayoutputstream out = new bytearrayoutputstream(); 
    marshaller.marshal( page, out ); 
    //将流转换并放入到inputstreamentity中 
    inputstreamentity inputstreamentity=new inputstreamentity(new bytearrayinputstream(out.tobytearray())); 
 
    //发送请求 
    closeablehttpclient httpclient = httpclients.createdefault(); 
    httpurirequest httppost = requestbuilder.put() 
        .seturi(new uri("http://172.16.200.220:8082/xwiki/rest/wikis/xwiki/spaces/main/pages/testpage")) 
        .setentity(inputstreamentity) 
        .setheader("content-type", "application/xml") 
        .setheader("cookie", cookiestr).build(); 
    //获取返回结果 
    closeablehttpresponse response = httpclient.execute(httppost); 
    system.out.println(response.getstatusline().getstatuscode()); 
    httpentity responseentity=response.getentity(); 
    system.out.println(responseentity); 
    if(response.getstatusline().getstatuscode()<400){ 
      page responsepage = (page) unmarshaller.unmarshal(responseentity.getcontent()); 
      system.out.println(responsepage); 
//      system.out.println(new gson().tojson(responsepage)); 
    } 
  } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!