try { LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); throw new SchemaRegistryException( "Error reading schema id returned by registerSchema call: headers.length = " + headers.length); } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) { throw new SchemaRegistryException( "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue()); } else { LOG.info("Registered schema successfully"); schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length());
/** * Return the header field * @param name the name of the header * @return the header field. * @see java.net.HttpURLConnection#getHeaderField(String) * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders() */ public String getHeaderField(String name) { LOG.trace("enter HttpURLConnection.getHeaderField(String)"); // Note: Return the last matching header in the Header[] array, as in // the JDK implementation. Header[] headers = this.method.getResponseHeaders(); for (int i = headers.length - 1; i >= 0; i--) { if (headers[i].getName().equalsIgnoreCase(name)) { return headers[i].getValue(); } } return null; }
String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
/** * Gets a header representing all of the header values with the given name. * If more that one header with the given name exists the values will be * combined with a "," as per RFC 2616. * * <p>Header name comparison is case insensitive. * * @param name the name of the header(s) to get * @return a header with a condensed value or <code>null</code> if no * headers by the given name are present */ public Header getCondensedHeader(String name) { Header[] headers = getHeaders(name); if (headers.length == 0) { return null; } else if (headers.length == 1) { return new Header(headers[0].getName(), headers[0].getValue()); } else { StringBuffer valueBuffer = new StringBuffer(headers[0].getValue()); for (int i = 1; i < headers.length; i++) { valueBuffer.append(", "); valueBuffer.append(headers[i].getValue()); } return new Header(name.toLowerCase(), valueBuffer.toString()); } }
private String getHttpResponse(String url) throws IOException { HttpClient client = new HttpClient(); HttpMethod get = new GetMethod(url); try { client.executeMethod(get); Header h = get.getResponseHeader("Refresh"); if (h != null) { String s = h.getValue(); int cut = s.indexOf("url="); if (cut >= 0) { response = get.getResponseBodyAsString(); log.debug("Job " + mrJobId + " get status check result.\n"); } else { get.releaseConnection();
protected String getHeader(String header) throws URISyntaxException, HttpException, IOException { HttpMethod head = new HeadMethod(url); int code = http.executeMethod(head); if(code != 200) { throw new IOException("Unable to retrieve from " + url); } Header theHeader = head.getResponseHeader(header); if(theHeader == null) { throw new IOException("No " + header + " header for " + url); } String val = theHeader.getValue(); return val; }
private void doRequest(String host, String url, int result) throws Exception { HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); try { int status = client.executeMethod(get); assertThat(result, is(status)); assertThat(get.getResponseHeader(WWW_AUTHENTICATE), not(nullValue())); assertThat(get.getResponseHeader(WWW_AUTHENTICATE).getValue(), containsString("mule-realm")); } finally { get.releaseConnection(); } }
private long getNoticeTimestamp(long noticeTime, HttpClient client) throws URISyntaxException, IOException, HttpException, ParseException { URI noticeURI = new URI(BASE_PROFILE_URI); HttpMethod method = new GetMethod(noticeURI.toString()); int statusCode = client.executeMethod(method); if (statusCode != SC_OK) { logger.warn("HTTP status " + statusCode + " while getting " + noticeURI); return -1; } Header h = method.getResponseHeader("Last-Modified"); if (h != null) return format.parse(h.getValue()).getTime(); return -1; }
private PAOSResponse requestPAOSResponse() throws ServiceException { GetMethod method = new GetMethod(getURL().toString()); method.addRequestHeader(new Header("Accept", "application/vnd.paos+xml")); method.addRequestHeader(new Header("PAOS", "ver='urn:liberty:paos:2003-08';'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'")); try { m_client.executeMethod(method); InputStream responseBodyStream = method.getResponseBodyAsStream(); PAOSResponse paosResponse = PAOSResponse.createFromXMLStream(responseBodyStream); return paosResponse; } catch (Exception e) { throw new ServiceException(String.format("Could not send basic GET request to <%s>.", getURL()), ServiceException.SERVICE_ERROR, e); } finally { method.releaseConnection(); } }
try { LOGGER.info("Trying to send request: {}.", firstPutReqString); int firstResponseCode = _httpClient.executeMethod(firstPutReq); if (firstResponseCode != 307) { LOGGER.error(String.format("Failed to execute the first PUT request to upload segment to webhdfs: %s. " + "Expected response code 307, but get %s. Response body: %s", firstPutReqString, firstResponseCode, firstPutReq.getResponseBodyAsString())); return false; return false; } finally { firstPutReq.releaseConnection(); String redirectedReqString = firstPutReq.getResponseHeader(LOCATION).getValue(); PutMethod redirectedReq = new PutMethod(redirectedReqString); File localFile = new File(localFilePath); int redirectedResponseCode = _httpClient.executeMethod(redirectedReq); if (redirectedResponseCode != 201) { LOGGER.error(String.format("Failed to execute the redirected PUT request to upload segment to webhdfs: %s. "
@Override public String getNewLocation(String oldUrl) { HttpMethod headMethod = null; try { HttpClient client = getClient(); (headMethod = new HeadMethod(oldUrl)).setFollowRedirects(false); if (HttpServletResponse.SC_MOVED_PERMANENTLY == client.executeMethod(headMethod)) return headMethod.getResponseHeader("Location").getValue(); } catch (IOException ioError) { log.error(String.format("IO error while trying to make a HEAD request to %s", oldUrl), ioError); } finally { if (null != headMethod) headMethod.releaseConnection(); } return oldUrl; }
errorString = "Exception while executing HttpMethod " + getMethod.getName() + " on URL " + downloadUrl; LOGGER.warn(errorString); Header contentLengthHeader = getMethod.getResponseHeader("Content-Length"); Header contentTypeHeader = getMethod.getResponseHeader("Content-Type"); } else { remoteSize = Long.parseLong(contentLengthHeader.getValue()); objectMetadata.setContentLength(remoteSize); if (contentTypeHeader.getValue() != null) { objectMetadata.setContentType(contentTypeHeader.getValue());
private Transferable initBasicResponseTransferable(HttpMethodBase method) throws IOException, HttpException { m_client.executeMethod(method); Header contentTypeHeader = method.getResponseHeader("Content-Type"); String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : ""; Transferable trans = TransferableFactory.getInstance().createStreamTransferable(contentType, method.getResponseBodyAsStream(), method.getResponseCharSet()); return trans; }
private boolean tryAndGetRemoteSize() { Header contentLengthHeader = request.getResponseHeader("Content-Length"); boolean chunked = false; long reportedRemoteSize = 0; if (contentLengthHeader == null) { Header chunkedHeader = request.getResponseHeader("Transfer-Encoding"); if (chunkedHeader == null || !"chunked".equalsIgnoreCase(chunkedHeader.getValue())) { status = Status.UNRECOVERABLE_ERROR; errorString = " Failed to receive length of download "; return false; } else if ("chunked".equalsIgnoreCase(chunkedHeader.getValue())) { chunked = true; } } else { reportedRemoteSize = Long.parseLong(contentLengthHeader.getValue()); if (reportedRemoteSize == 0) { status = Status.DOWNLOAD_FINISHED; String downloaded = "(download complete remote=" + remoteSize + "bytes)"; errorString = "Downloaded " + totalBytes + " bytes " + downloaded; downloadTime = 0; return false; } } if (remoteSize == 0) { remoteSize = reportedRemoteSize; } return true; }
throws RedirectException { Header locationHeader = method.getResponseHeader("location"); if (locationHeader == null) { LOG.error("Received redirect response " + method.getStatusCode() + " but no location header"); return false; String location = locationHeader.getValue(); if (LOG.isDebugEnabled()) { LOG.debug("Redirect requested to location '" + location + "'"); this.conn.getHost(), this.conn.getPort(), method.getPath() ); String charset = method.getParams().getUriCharset(); redirectUri = new URI(location, true, charset); method.getParams().setDefaults(this.params); method.setURI(redirectUri);
/** * Returns an array of {@link HeaderElement}s * constructed from my value. * * @see HeaderElement#parseElements(String) * * @return an array of header elements * * @since 3.0 */ public HeaderElement[] getElements() { return HeaderElement.parseElements(getValue()); }
@Override public HttpVersion getProtocol() { org.apache.commons.httpclient.HttpVersion version = httpMethod .getParams().getVersion(); if (version == null) { return null; } Header connection = httpMethod.getResponseHeader("Connection"); if (protocol == null) { protocol = new HttpVersion("HTTP", version.getMajor(), version.getMinor(), connection != null && KEEP_ALIVE.equalsIgnoreCase(connection .getValue())); } return protocol; }
public GetMethod getMethod(Map<String, String> requestHeaders) { GetMethod getMethod = new GetMethod(); if (!requestHeaders.isEmpty()) { for (String headerName : requestHeaders.keySet()) { Header header = new Header(headerName, requestHeaders.get(headerName)); getMethod.addRequestHeader(header); } } return getMethod; }
private String responseToErrorMessage(final HttpMethodBase method) { assert method.isRequestSent() : "no use getting an error message unless the request is sent"; if ("text/html".equals(method.getResponseHeader(CONTENT_TYPE).getValue())) { // The error message is the response content // Safety margin of 2048 characters, anything longer is probably useless // and will clutter the logs try { return method.getResponseBodyAsString(2048); } catch (IOException e) { S_LOGGER.debug("Error while loading response body", e); } } // The default return method.getStatusText(); }