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