1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.io.BufferedOutputStream;
|
---|
7 | import java.io.BufferedReader;
|
---|
8 | import java.io.IOException;
|
---|
9 | import java.io.InputStream;
|
---|
10 | import java.io.OutputStream;
|
---|
11 | import java.net.HttpRetryException;
|
---|
12 | import java.net.HttpURLConnection;
|
---|
13 | import java.net.URL;
|
---|
14 | import java.util.List;
|
---|
15 | import java.util.Locale;
|
---|
16 | import java.util.Map;
|
---|
17 | import java.util.Scanner;
|
---|
18 | import java.util.TreeMap;
|
---|
19 | import java.util.regex.Matcher;
|
---|
20 | import java.util.regex.Pattern;
|
---|
21 | import java.util.zip.GZIPInputStream;
|
---|
22 |
|
---|
23 | import org.openstreetmap.josm.Main;
|
---|
24 | import org.openstreetmap.josm.data.Version;
|
---|
25 | import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
|
---|
26 | import org.openstreetmap.josm.gui.progress.ProgressMonitor;
|
---|
27 | import org.openstreetmap.josm.io.Compression;
|
---|
28 | import org.openstreetmap.josm.io.ProgressInputStream;
|
---|
29 | import org.openstreetmap.josm.io.ProgressOutputStream;
|
---|
30 | import org.openstreetmap.josm.io.UTFInputStreamReader;
|
---|
31 |
|
---|
32 | /**
|
---|
33 | * Provides a uniform access for a HTTP/HTTPS server. This class should be used in favour of {@link HttpURLConnection}.
|
---|
34 | * @since 9168
|
---|
35 | */
|
---|
36 | public final class HttpClient {
|
---|
37 |
|
---|
38 | private URL url;
|
---|
39 | private final String requestMethod;
|
---|
40 | private int connectTimeout = Main.pref.getInteger("socket.timeout.connect", 15) * 1000;
|
---|
41 | private int readTimeout = Main.pref.getInteger("socket.timeout.read", 30) * 1000;
|
---|
42 | private byte[] requestBody;
|
---|
43 | private long ifModifiedSince;
|
---|
44 | private long contentLength;
|
---|
45 | private final Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
---|
46 | private int maxRedirects = Main.pref.getInteger("socket.maxredirects", 5);
|
---|
47 | private boolean useCache;
|
---|
48 | private String reasonForRequest;
|
---|
49 |
|
---|
50 | private HttpClient(URL url, String requestMethod) {
|
---|
51 | this.url = url;
|
---|
52 | this.requestMethod = requestMethod;
|
---|
53 | this.headers.put("Accept-Encoding", "gzip");
|
---|
54 | }
|
---|
55 |
|
---|
56 | /**
|
---|
57 | * Opens the HTTP connection.
|
---|
58 | * @return HTTP response
|
---|
59 | * @throws IOException if any I/O error occurs
|
---|
60 | */
|
---|
61 | public Response connect() throws IOException {
|
---|
62 | return connect(null);
|
---|
63 | }
|
---|
64 |
|
---|
65 | /**
|
---|
66 | * Opens the HTTP connection.
|
---|
67 | * @param progressMonitor progress monitor
|
---|
68 | * @return HTTP response
|
---|
69 | * @throws IOException if any I/O error occurs
|
---|
70 | * @since 9179
|
---|
71 | */
|
---|
72 | public Response connect(ProgressMonitor progressMonitor) throws IOException {
|
---|
73 | if (progressMonitor == null) {
|
---|
74 | progressMonitor = NullProgressMonitor.INSTANCE;
|
---|
75 | }
|
---|
76 | final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
---|
77 | connection.setRequestMethod(requestMethod);
|
---|
78 | connection.setRequestProperty("User-Agent", Version.getInstance().getFullAgentString());
|
---|
79 | connection.setConnectTimeout(connectTimeout);
|
---|
80 | connection.setReadTimeout(readTimeout);
|
---|
81 | connection.setInstanceFollowRedirects(false); // we do that ourselves
|
---|
82 | if (ifModifiedSince > 0) {
|
---|
83 | connection.setIfModifiedSince(ifModifiedSince);
|
---|
84 | }
|
---|
85 | if (contentLength > 0) {
|
---|
86 | connection.setFixedLengthStreamingMode(contentLength);
|
---|
87 | }
|
---|
88 | connection.setUseCaches(useCache);
|
---|
89 | if (!useCache) {
|
---|
90 | connection.setRequestProperty("Cache-Control", "no-cache");
|
---|
91 | }
|
---|
92 | for (Map.Entry<String, String> header : headers.entrySet()) {
|
---|
93 | if (header.getValue() != null) {
|
---|
94 | connection.setRequestProperty(header.getKey(), header.getValue());
|
---|
95 | }
|
---|
96 | }
|
---|
97 |
|
---|
98 | progressMonitor.beginTask(tr("Contacting Server..."), 1);
|
---|
99 | progressMonitor.indeterminateSubTask(null);
|
---|
100 |
|
---|
101 | if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
|
---|
102 | Main.info("{0} {1} ({2}) ...", requestMethod, url, Utils.getSizeString(requestBody.length, Locale.getDefault()));
|
---|
103 | headers.put("Content-Length", String.valueOf(requestBody.length));
|
---|
104 | connection.setDoOutput(true);
|
---|
105 | try (OutputStream out = new BufferedOutputStream(
|
---|
106 | new ProgressOutputStream(connection.getOutputStream(), requestBody.length, progressMonitor))) {
|
---|
107 | out.write(requestBody);
|
---|
108 | }
|
---|
109 | }
|
---|
110 |
|
---|
111 | boolean successfulConnection = false;
|
---|
112 | try {
|
---|
113 | try {
|
---|
114 | connection.connect();
|
---|
115 | final boolean hasReason = reasonForRequest != null && !reasonForRequest.isEmpty();
|
---|
116 | Main.info("{0} {1}{2} -> {3}{4}",
|
---|
117 | requestMethod, url, hasReason ? " (" + reasonForRequest + ")" : "",
|
---|
118 | connection.getResponseCode(),
|
---|
119 | connection.getContentLengthLong() > 0
|
---|
120 | ? " (" + Utils.getSizeString(connection.getContentLengthLong(), Locale.getDefault()) + ")"
|
---|
121 | : ""
|
---|
122 | );
|
---|
123 | if (Main.isDebugEnabled()) {
|
---|
124 | Main.debug("RESPONSE: " + connection.getHeaderFields());
|
---|
125 | }
|
---|
126 | } catch (IOException e) {
|
---|
127 | Main.info("{0} {1} -> !!!", requestMethod, url);
|
---|
128 | Main.warn(e);
|
---|
129 | //noinspection ThrowableResultOfMethodCallIgnored
|
---|
130 | Main.addNetworkError(url, Utils.getRootCause(e));
|
---|
131 | throw e;
|
---|
132 | }
|
---|
133 | if (isRedirect(connection.getResponseCode())) {
|
---|
134 | final String redirectLocation = connection.getHeaderField("Location");
|
---|
135 | if (redirectLocation == null) {
|
---|
136 | /* I18n: argument is HTTP response code */
|
---|
137 | String msg = tr("Unexpected response from HTTP server. Got {0} response without ''Location'' header." +
|
---|
138 | " Can''t redirect. Aborting.", connection.getResponseCode());
|
---|
139 | throw new IOException(msg);
|
---|
140 | } else if (maxRedirects > 0) {
|
---|
141 | url = new URL(url, redirectLocation);
|
---|
142 | maxRedirects--;
|
---|
143 | Main.info(tr("Download redirected to ''{0}''", redirectLocation));
|
---|
144 | return connect();
|
---|
145 | } else if (maxRedirects == 0) {
|
---|
146 | String msg = tr("Too many redirects to the download URL detected. Aborting.");
|
---|
147 | throw new IOException(msg);
|
---|
148 | }
|
---|
149 | }
|
---|
150 | Response response = new Response(connection, progressMonitor);
|
---|
151 | successfulConnection = true;
|
---|
152 | return response;
|
---|
153 | } finally {
|
---|
154 | if (!successfulConnection) {
|
---|
155 | connection.disconnect();
|
---|
156 | }
|
---|
157 | }
|
---|
158 | }
|
---|
159 |
|
---|
160 | /**
|
---|
161 | * A wrapper for the HTTP response.
|
---|
162 | */
|
---|
163 | public static final class Response {
|
---|
164 | private final HttpURLConnection connection;
|
---|
165 | private final ProgressMonitor monitor;
|
---|
166 | private final int responseCode;
|
---|
167 | private final String responseMessage;
|
---|
168 | private boolean uncompress;
|
---|
169 | private boolean uncompressAccordingToContentDisposition;
|
---|
170 |
|
---|
171 | private Response(HttpURLConnection connection, ProgressMonitor monitor) throws IOException {
|
---|
172 | CheckParameterUtil.ensureParameterNotNull(connection, "connection");
|
---|
173 | CheckParameterUtil.ensureParameterNotNull(monitor, "monitor");
|
---|
174 | this.connection = connection;
|
---|
175 | this.monitor = monitor;
|
---|
176 | this.responseCode = connection.getResponseCode();
|
---|
177 | this.responseMessage = connection.getResponseMessage();
|
---|
178 | }
|
---|
179 |
|
---|
180 | /**
|
---|
181 | * Sets whether {@link #getContent()} should uncompress the input stream if necessary.
|
---|
182 | *
|
---|
183 | * @param uncompress whether the input stream should be uncompressed if necessary
|
---|
184 | * @return {@code this}
|
---|
185 | */
|
---|
186 | public Response uncompress(boolean uncompress) {
|
---|
187 | this.uncompress = uncompress;
|
---|
188 | return this;
|
---|
189 | }
|
---|
190 |
|
---|
191 | /**
|
---|
192 | * Sets whether {@link #getContent()} should uncompress the input stream according to {@code Content-Disposition}
|
---|
193 | * HTTP header.
|
---|
194 | * @param uncompressAccordingToContentDisposition whether the input stream should be uncompressed according to
|
---|
195 | * {@code Content-Disposition}
|
---|
196 | * @return {@code this}
|
---|
197 | * @since 9172
|
---|
198 | */
|
---|
199 | public Response uncompressAccordingToContentDisposition(boolean uncompressAccordingToContentDisposition) {
|
---|
200 | this.uncompressAccordingToContentDisposition = uncompressAccordingToContentDisposition;
|
---|
201 | return this;
|
---|
202 | }
|
---|
203 |
|
---|
204 | /**
|
---|
205 | * Returns the URL.
|
---|
206 | * @return the URL
|
---|
207 | * @see HttpURLConnection#getURL()
|
---|
208 | * @since 9172
|
---|
209 | */
|
---|
210 | public URL getURL() {
|
---|
211 | return connection.getURL();
|
---|
212 | }
|
---|
213 |
|
---|
214 | /**
|
---|
215 | * Returns the request method.
|
---|
216 | * @return the HTTP request method
|
---|
217 | * @see HttpURLConnection#getRequestMethod()
|
---|
218 | * @since 9172
|
---|
219 | */
|
---|
220 | public String getRequestMethod() {
|
---|
221 | return connection.getRequestMethod();
|
---|
222 | }
|
---|
223 |
|
---|
224 | /**
|
---|
225 | * Returns an input stream that reads from this HTTP connection, or,
|
---|
226 | * error stream if the connection failed but the server sent useful data.
|
---|
227 | * <p>
|
---|
228 | * Note: the return value can be null, if both the input and the error stream are null.
|
---|
229 | * Seems to be the case if the OSM server replies a 401 Unauthorized, see #3887
|
---|
230 | * @return input or error stream
|
---|
231 | * @throws IOException if any I/O error occurs
|
---|
232 | *
|
---|
233 | * @see HttpURLConnection#getInputStream()
|
---|
234 | * @see HttpURLConnection#getErrorStream()
|
---|
235 | */
|
---|
236 | @SuppressWarnings("resource")
|
---|
237 | public InputStream getContent() throws IOException {
|
---|
238 | InputStream in;
|
---|
239 | try {
|
---|
240 | in = connection.getInputStream();
|
---|
241 | } catch (IOException ioe) {
|
---|
242 | in = connection.getErrorStream();
|
---|
243 | }
|
---|
244 | if (in != null) {
|
---|
245 | in = new ProgressInputStream(in, getContentLength(), monitor);
|
---|
246 | in = "gzip".equalsIgnoreCase(getContentEncoding()) ? new GZIPInputStream(in) : in;
|
---|
247 | Compression compression = Compression.NONE;
|
---|
248 | if (uncompress) {
|
---|
249 | final String contentType = getContentType();
|
---|
250 | Main.debug("Uncompressing input stream according to Content-Type header: {0}", contentType);
|
---|
251 | compression = Compression.forContentType(contentType);
|
---|
252 | }
|
---|
253 | if (uncompressAccordingToContentDisposition && Compression.NONE.equals(compression)) {
|
---|
254 | final String contentDisposition = getHeaderField("Content-Disposition");
|
---|
255 | final Matcher matcher = Pattern.compile("filename=\"([^\"]+)\"").matcher(contentDisposition);
|
---|
256 | if (matcher.find()) {
|
---|
257 | Main.debug("Uncompressing input stream according to Content-Disposition header: {0}", contentDisposition);
|
---|
258 | compression = Compression.byExtension(matcher.group(1));
|
---|
259 | }
|
---|
260 | }
|
---|
261 | in = compression.getUncompressedInputStream(in);
|
---|
262 | }
|
---|
263 | return in;
|
---|
264 | }
|
---|
265 |
|
---|
266 | /**
|
---|
267 | * Returns {@link #getContent()} wrapped in a buffered reader.
|
---|
268 | *
|
---|
269 | * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}.
|
---|
270 | * @return buffered reader
|
---|
271 | * @throws IOException if any I/O error occurs
|
---|
272 | */
|
---|
273 | public BufferedReader getContentReader() throws IOException {
|
---|
274 | return new BufferedReader(
|
---|
275 | UTFInputStreamReader.create(getContent())
|
---|
276 | );
|
---|
277 | }
|
---|
278 |
|
---|
279 | /**
|
---|
280 | * Fetches the HTTP response as String.
|
---|
281 | * @return the response
|
---|
282 | * @throws IOException if any I/O error occurs
|
---|
283 | */
|
---|
284 | @SuppressWarnings("resource")
|
---|
285 | public String fetchContent() throws IOException {
|
---|
286 | try (Scanner scanner = new Scanner(getContentReader()).useDelimiter("\\A")) {
|
---|
287 | return scanner.hasNext() ? scanner.next() : "";
|
---|
288 | }
|
---|
289 | }
|
---|
290 |
|
---|
291 | /**
|
---|
292 | * Gets the response code from this HTTP connection.
|
---|
293 | * @return HTTP response code
|
---|
294 | *
|
---|
295 | * @see HttpURLConnection#getResponseCode()
|
---|
296 | */
|
---|
297 | public int getResponseCode() {
|
---|
298 | return responseCode;
|
---|
299 | }
|
---|
300 |
|
---|
301 | /**
|
---|
302 | * Gets the response message from this HTTP connection.
|
---|
303 | * @return HTTP response message
|
---|
304 | *
|
---|
305 | * @see HttpURLConnection#getResponseMessage()
|
---|
306 | * @since 9172
|
---|
307 | */
|
---|
308 | public String getResponseMessage() {
|
---|
309 | return responseMessage;
|
---|
310 | }
|
---|
311 |
|
---|
312 | /**
|
---|
313 | * Returns the {@code Content-Encoding} header.
|
---|
314 | * @return {@code Content-Encoding} HTTP header
|
---|
315 | * @see HttpURLConnection#getContentEncoding()
|
---|
316 | */
|
---|
317 | public String getContentEncoding() {
|
---|
318 | return connection.getContentEncoding();
|
---|
319 | }
|
---|
320 |
|
---|
321 | /**
|
---|
322 | * Returns the {@code Content-Type} header.
|
---|
323 | * @return {@code Content-Type} HTTP header
|
---|
324 | */
|
---|
325 | public String getContentType() {
|
---|
326 | return connection.getHeaderField("Content-Type");
|
---|
327 | }
|
---|
328 |
|
---|
329 | /**
|
---|
330 | * Returns the {@code Expire} header.
|
---|
331 | * @return {@code Expire} HTTP header
|
---|
332 | * @see HttpURLConnection#getExpiration()
|
---|
333 | * @since 9232
|
---|
334 | */
|
---|
335 | public long getExpiration() {
|
---|
336 | return connection.getExpiration();
|
---|
337 | }
|
---|
338 |
|
---|
339 | /**
|
---|
340 | * Returns the {@code Last-Modified} header.
|
---|
341 | * @return {@code Last-Modified} HTTP header
|
---|
342 | * @see HttpURLConnection#getLastModified()
|
---|
343 | * @since 9232
|
---|
344 | */
|
---|
345 | public long getLastModified() {
|
---|
346 | return connection.getLastModified();
|
---|
347 | }
|
---|
348 |
|
---|
349 | /**
|
---|
350 | * Returns the {@code Content-Length} header.
|
---|
351 | * @return {@code Content-Length} HTTP header
|
---|
352 | * @see HttpURLConnection#getContentLengthLong()
|
---|
353 | */
|
---|
354 | public long getContentLength() {
|
---|
355 | return connection.getContentLengthLong();
|
---|
356 | }
|
---|
357 |
|
---|
358 | /**
|
---|
359 | * Returns the value of the named header field.
|
---|
360 | * @param name the name of a header field
|
---|
361 | * @return the value of the named header field, or {@code null} if there is no such field in the header
|
---|
362 | * @see HttpURLConnection#getHeaderField(String)
|
---|
363 | * @since 9172
|
---|
364 | */
|
---|
365 | public String getHeaderField(String name) {
|
---|
366 | return connection.getHeaderField(name);
|
---|
367 | }
|
---|
368 |
|
---|
369 | /**
|
---|
370 | * Returns an unmodifiable Map mapping header keys to a List of header values.
|
---|
371 | * @return unmodifiable Map mapping header keys to a List of header values
|
---|
372 | * @see HttpURLConnection#getHeaderFields()
|
---|
373 | * @since 9232
|
---|
374 | */
|
---|
375 | public Map<String, List<String>> getHeaderFields() {
|
---|
376 | return connection.getHeaderFields();
|
---|
377 | }
|
---|
378 |
|
---|
379 | /**
|
---|
380 | * @see HttpURLConnection#disconnect()
|
---|
381 | */
|
---|
382 | public void disconnect() {
|
---|
383 | // TODO is this block necessary for disconnecting?
|
---|
384 | // Fix upload aborts - see #263
|
---|
385 | connection.setConnectTimeout(100);
|
---|
386 | connection.setReadTimeout(100);
|
---|
387 | try {
|
---|
388 | Thread.sleep(100);
|
---|
389 | } catch (InterruptedException ex) {
|
---|
390 | Main.warn("InterruptedException in " + getClass().getSimpleName() + " during cancel");
|
---|
391 | }
|
---|
392 |
|
---|
393 | connection.disconnect();
|
---|
394 | }
|
---|
395 | }
|
---|
396 |
|
---|
397 | /**
|
---|
398 | * Creates a new instance for the given URL and a {@code GET} request
|
---|
399 | *
|
---|
400 | * @param url the URL
|
---|
401 | * @return a new instance
|
---|
402 | */
|
---|
403 | public static HttpClient create(URL url) {
|
---|
404 | return create(url, "GET");
|
---|
405 | }
|
---|
406 |
|
---|
407 | /**
|
---|
408 | * Creates a new instance for the given URL and a {@code GET} request
|
---|
409 | *
|
---|
410 | * @param url the URL
|
---|
411 | * @param requestMethod the HTTP request method to perform when calling
|
---|
412 | * @return a new instance
|
---|
413 | */
|
---|
414 | public static HttpClient create(URL url, String requestMethod) {
|
---|
415 | return new HttpClient(url, requestMethod);
|
---|
416 | }
|
---|
417 |
|
---|
418 | /**
|
---|
419 | * Returns the URL set for this connection.
|
---|
420 | * @return the URL
|
---|
421 | * @see #create(URL)
|
---|
422 | * @see #create(URL, String)
|
---|
423 | * @since 9172
|
---|
424 | */
|
---|
425 | public URL getURL() {
|
---|
426 | return url;
|
---|
427 | }
|
---|
428 |
|
---|
429 | /**
|
---|
430 | * Returns the request method set for this connection.
|
---|
431 | * @return the HTTP request method
|
---|
432 | * @see #create(URL, String)
|
---|
433 | * @since 9172
|
---|
434 | */
|
---|
435 | public String getRequestMethod() {
|
---|
436 | return requestMethod;
|
---|
437 | }
|
---|
438 |
|
---|
439 | /**
|
---|
440 | * Returns the set value for the given {@code header}.
|
---|
441 | * @param header HTTP header name
|
---|
442 | * @return HTTP header value
|
---|
443 | * @since 9172
|
---|
444 | */
|
---|
445 | public String getRequestHeader(String header) {
|
---|
446 | return headers.get(header);
|
---|
447 | }
|
---|
448 |
|
---|
449 | /**
|
---|
450 | * Sets whether not to set header {@code Cache-Control=no-cache}
|
---|
451 | *
|
---|
452 | * @param useCache whether not to set header {@code Cache-Control=no-cache}
|
---|
453 | * @return {@code this}
|
---|
454 | * @see HttpURLConnection#setUseCaches(boolean)
|
---|
455 | */
|
---|
456 | public HttpClient useCache(boolean useCache) {
|
---|
457 | this.useCache = useCache;
|
---|
458 | return this;
|
---|
459 | }
|
---|
460 |
|
---|
461 | /**
|
---|
462 | * Sets whether not to set header {@code Connection=close}
|
---|
463 | * <p>
|
---|
464 | * This might fix #7640, see
|
---|
465 | * <a href='https://web.archive.org/web/20140118201501/http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive'>here</a>.
|
---|
466 | *
|
---|
467 | * @param keepAlive whether not to set header {@code Connection=close}
|
---|
468 | * @return {@code this}
|
---|
469 | */
|
---|
470 | public HttpClient keepAlive(boolean keepAlive) {
|
---|
471 | return setHeader("Connection", keepAlive ? null : "close");
|
---|
472 | }
|
---|
473 |
|
---|
474 | /**
|
---|
475 | * Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced
|
---|
476 | * by this URLConnection. If the timeout expires before the connection can be established, a
|
---|
477 | * {@link java.net.SocketTimeoutException} is raised. A timeout of zero is interpreted as an infinite timeout.
|
---|
478 | * @param connectTimeout an {@code int} that specifies the connect timeout value in milliseconds
|
---|
479 | * @return {@code this}
|
---|
480 | * @see HttpURLConnection#setConnectTimeout(int)
|
---|
481 | */
|
---|
482 | public HttpClient setConnectTimeout(int connectTimeout) {
|
---|
483 | this.connectTimeout = connectTimeout;
|
---|
484 | return this;
|
---|
485 | }
|
---|
486 |
|
---|
487 | /**
|
---|
488 | * Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeout when reading from
|
---|
489 | * input stream when a connection is established to a resource. If the timeout expires before there is data available for
|
---|
490 | * read, a {@link java.net.SocketTimeoutException} is raised. A timeout of zero is interpreted as an infinite timeout.
|
---|
491 | * @param readTimeout an {@code int} that specifies the read timeout value in milliseconds
|
---|
492 | * @return {@code this}
|
---|
493 | * @see HttpURLConnection#setReadTimeout(int)
|
---|
494 | */
|
---|
495 | public HttpClient setReadTimeout(int readTimeout) {
|
---|
496 | this.readTimeout = readTimeout;
|
---|
497 | return this;
|
---|
498 | }
|
---|
499 |
|
---|
500 | /**
|
---|
501 | * This method is used to enable streaming of a HTTP request body without internal buffering,
|
---|
502 | * when the content length is known in advance.
|
---|
503 | * <p>
|
---|
504 | * An exception will be thrown if the application attempts to write more data than the indicated content-length,
|
---|
505 | * or if the application closes the OutputStream before writing the indicated amount.
|
---|
506 | * <p>
|
---|
507 | * When output streaming is enabled, authentication and redirection cannot be handled automatically.
|
---|
508 | * A {@linkplain HttpRetryException} will be thrown when reading the response if authentication or redirection
|
---|
509 | * are required. This exception can be queried for the details of the error.
|
---|
510 | *
|
---|
511 | * @param contentLength The number of bytes which will be written to the OutputStream
|
---|
512 | * @return {@code this}
|
---|
513 | * @see HttpURLConnection#setFixedLengthStreamingMode(long)
|
---|
514 | * @since 9178
|
---|
515 | */
|
---|
516 | public HttpClient setFixedLengthStreamingMode(long contentLength) {
|
---|
517 | this.contentLength = contentLength;
|
---|
518 | return this;
|
---|
519 | }
|
---|
520 |
|
---|
521 | /**
|
---|
522 | * Sets the {@code Accept} header.
|
---|
523 | * @param accept header value
|
---|
524 | *
|
---|
525 | * @return {@code this}
|
---|
526 | */
|
---|
527 | public HttpClient setAccept(String accept) {
|
---|
528 | return setHeader("Accept", accept);
|
---|
529 | }
|
---|
530 |
|
---|
531 | /**
|
---|
532 | * Sets the request body for {@code PUT}/{@code POST} requests.
|
---|
533 | * @param requestBody request body
|
---|
534 | *
|
---|
535 | * @return {@code this}
|
---|
536 | */
|
---|
537 | public HttpClient setRequestBody(byte[] requestBody) {
|
---|
538 | this.requestBody = requestBody;
|
---|
539 | return this;
|
---|
540 | }
|
---|
541 |
|
---|
542 | /**
|
---|
543 | * Sets the {@code If-Modified-Since} header.
|
---|
544 | * @param ifModifiedSince header value
|
---|
545 | *
|
---|
546 | * @return {@code this}
|
---|
547 | */
|
---|
548 | public HttpClient setIfModifiedSince(long ifModifiedSince) {
|
---|
549 | this.ifModifiedSince = ifModifiedSince;
|
---|
550 | return this;
|
---|
551 | }
|
---|
552 |
|
---|
553 | /**
|
---|
554 | * Sets the maximum number of redirections to follow.
|
---|
555 | *
|
---|
556 | * Set {@code maxRedirects} to {@code -1} in order to ignore redirects, i.e.,
|
---|
557 | * to not throw an {@link IOException} in {@link #connect()}.
|
---|
558 | * @param maxRedirects header value
|
---|
559 | *
|
---|
560 | * @return {@code this}
|
---|
561 | */
|
---|
562 | public HttpClient setMaxRedirects(int maxRedirects) {
|
---|
563 | this.maxRedirects = maxRedirects;
|
---|
564 | return this;
|
---|
565 | }
|
---|
566 |
|
---|
567 | /**
|
---|
568 | * Sets an arbitrary HTTP header.
|
---|
569 | * @param key header name
|
---|
570 | * @param value header value
|
---|
571 | *
|
---|
572 | * @return {@code this}
|
---|
573 | */
|
---|
574 | public HttpClient setHeader(String key, String value) {
|
---|
575 | this.headers.put(key, value);
|
---|
576 | return this;
|
---|
577 | }
|
---|
578 |
|
---|
579 | /**
|
---|
580 | * Sets arbitrary HTTP headers.
|
---|
581 | * @param headers HTTP headers
|
---|
582 | *
|
---|
583 | * @return {@code this}
|
---|
584 | */
|
---|
585 | public HttpClient setHeaders(Map<String, String> headers) {
|
---|
586 | this.headers.putAll(headers);
|
---|
587 | return this;
|
---|
588 | }
|
---|
589 |
|
---|
590 | /**
|
---|
591 | * Sets a reason to show on console. Can be {@code null} if no reason is given.
|
---|
592 | * @param reasonForRequest Reason to show
|
---|
593 | * @return {@code this}
|
---|
594 | * @since 9172
|
---|
595 | */
|
---|
596 | public HttpClient setReasonForRequest(String reasonForRequest) {
|
---|
597 | this.reasonForRequest = reasonForRequest;
|
---|
598 | return this;
|
---|
599 | }
|
---|
600 |
|
---|
601 | private static boolean isRedirect(final int statusCode) {
|
---|
602 | switch (statusCode) {
|
---|
603 | case HttpURLConnection.HTTP_MOVED_PERM: // 301
|
---|
604 | case HttpURLConnection.HTTP_MOVED_TEMP: // 302
|
---|
605 | case HttpURLConnection.HTTP_SEE_OTHER: // 303
|
---|
606 | case 307: // TEMPORARY_REDIRECT:
|
---|
607 | case 308: // PERMANENT_REDIRECT:
|
---|
608 | return true;
|
---|
609 | default:
|
---|
610 | return false;
|
---|
611 | }
|
---|
612 | }
|
---|
613 | }
|
---|