java 中HttpClient傳輸xml字符串實例詳解
介紹:我現在有一個對象page,需要將page對象轉換為xml格式并以binary方式傳輸到服務端
其中涉及到的技術點有:
1、對象轉xml流
2、輸出流轉輸入流
3、httpClient發送二進制流數據
POM文件依賴配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
< 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代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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)); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/gsying1474/article/details/51505714