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

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

网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、小程序设计、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了佳县免费建站欢迎大家使用!

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

其中涉及到的技术点有:

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

POM文件依赖配置

 
   
    junit 
    junit 
    3.8.1 
    test 
   
   
    org.apache.httpcomponents 
    httpclient 
    4.5.2 
   
   
   
   org.apache.httpcomponents 
   httpmime 
   4.5.2 
   
   
    commons-lang 
    commons-lang 
    2.4 
   
   
    com.google.code.gson 
    gson 
    2.2.4 
    jar 
    compile 
   
   
    org.xwiki.platform 
    xwiki-platform-rest-model 
    7.2 
   
 

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)); 
    } 
  } 

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


网页标题:java中HttpClient传输xml字符串实例详解
标题网址:http://hbruida.cn/article/pjcsis.html