java HttpClient transfer xml string instance detail
- 2020-06-23 00:32:11
- OfStack
HttpClient transfer xml string instance detail in java
Description: I now have 1 object page and need to convert the page object to xml format and transfer it to the server as binary
The technical points involved include:
1. Turn the object to xml stream
2, output flow input stream
3. httpClient sends data in base 2 stream
The POM file depends on the configuration
<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 code example
public void testNewPage() throws Exception{
// Define the object
Page page =new Page();
page.setTitle("testPage");
page.setSyntax("xwiki/2.0");
page.setContent("This is a testPage");
page.setId("xwiki:Main.testPage");
// Initialize and transform the object to xml File stream
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 );
// Convert and put the stream into InputStreamEntity In the
InputStreamEntity inputStreamEntity=new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()));
// Send the request
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();
// Get the return result
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));
}
}
Thank you for reading, I hope to help you, thank you for your support to this site!