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 package org.apache.hc.client5.http.examples.fluent;
28
29 import java.io.IOException;
30 import java.nio.charset.Charset;
31 import java.nio.charset.StandardCharsets;
32
33 import javax.xml.parsers.DocumentBuilder;
34 import javax.xml.parsers.DocumentBuilderFactory;
35 import javax.xml.parsers.ParserConfigurationException;
36
37 import org.apache.hc.client5.http.ClientProtocolException;
38 import org.apache.hc.client5.http.HttpResponseException;
39 import org.apache.hc.client5.http.fluent.Request;
40 import org.apache.hc.core5.http.ClassicHttpResponse;
41 import org.apache.hc.core5.http.ContentType;
42 import org.apache.hc.core5.http.HttpEntity;
43 import org.apache.hc.core5.http.HttpStatus;
44 import org.apache.hc.core5.http.io.HttpClientResponseHandler;
45 import org.w3c.dom.Document;
46 import org.xml.sax.SAXException;
47
48
49
50
51
52 public class FluentResponseHandling {
53
54 public static void main(final String... args)throws Exception {
55 final Document result = Request.get("http://somehost/content")
56 .execute().handleResponse(new HttpClientResponseHandler<Document>() {
57
58 @Override
59 public Document handleResponse(final ClassicHttpResponse response) throws IOException {
60 final int status = response.getCode();
61 final HttpEntity entity = response.getEntity();
62 if (status >= HttpStatus.SC_REDIRECTION) {
63 throw new HttpResponseException(status, response.getReasonPhrase());
64 }
65 if (entity == null) {
66 throw new ClientProtocolException("Response contains no content");
67 }
68 final DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
69 try {
70 final DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
71 final ContentType contentType = ContentType.parseLenient(entity.getContentType());
72 if (!contentType.equals(ContentType.APPLICATION_XML)) {
73 throw new ClientProtocolException("Unexpected content type:" + contentType);
74 }
75 Charset charset = contentType.getCharset();
76 if (charset == null) {
77 charset = StandardCharsets.ISO_8859_1;
78 }
79 return docBuilder.parse(entity.getContent(), charset.name());
80 } catch (final ParserConfigurationException ex) {
81 throw new IllegalStateException(ex);
82 } catch (final SAXException ex) {
83 throw new ClientProtocolException("Malformed XML document", ex);
84 }
85 }
86
87 });
88
89 System.out.println(result);
90 }
91
92 }