1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.maven.issue.util;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20
21 import org.apache.commons.httpclient.Header;
22 import org.apache.commons.httpclient.HttpMethod;
23 import org.apache.commons.io.IOUtils;
24 import org.xml.sax.InputSource;
25
26 import de.smartics.maven.issue.command.CommandException;
27
28
29
30
31 public final class HttpClientUtils
32 {
33
34
35
36
37
38
39
40
41
42
43
44
45
46 private HttpClientUtils()
47 {
48 }
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 public static String readBodyContent(final HttpMethod method)
67 {
68 InputStream input = null;
69 try
70 {
71 input = method.getResponseBodyAsStream();
72 final String encoding = getEncoding(method);
73 final String content = IOUtils.toString(input, encoding);
74 return content;
75 }
76 catch (final IOException e)
77 {
78 throw new CommandException("Problems reading respose.", e);
79 }
80 finally
81 {
82 IOUtils.closeQuietly(input);
83 }
84 }
85
86
87
88
89
90
91
92 public static InputSource readBodyContentAsStream(final HttpMethod method)
93 {
94 InputStream input = null;
95 try
96 {
97 input = method.getResponseBodyAsStream();
98 final String encoding = getEncoding(method);
99 final InputSource source = new InputSource(input);
100 source.setEncoding(encoding);
101 return source;
102 }
103 catch (final IOException e)
104 {
105 throw new CommandException("Problems reading respose.", e);
106 }
107 }
108
109 private static String getEncoding(final HttpMethod method)
110 {
111 final Header header = method.getResponseHeader("Content-Type");
112 if (header != null)
113 {
114 final String pattern = "; charset=";
115 final String value = header.getValue();
116 final int delimiterIndex = value.lastIndexOf(pattern);
117 if (delimiterIndex != -1)
118 {
119 final int start = delimiterIndex + pattern.length();
120 if (start < value.length() - 1)
121 {
122 final String encoding = value.substring(start).trim();
123 return encoding;
124 }
125 }
126 }
127 return null;
128 }
129
130
131
132 }