List of usage examples for org.apache.http.client.methods HttpHead HttpHead
public HttpHead(final String uri)
From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java
@Override public <T> T doHead(String url, ResponseHandler<? extends T> responseHandler) throws IOException { HttpHead head = new HttpHead(url); return execute(head, responseHandler); }
From source file:com.hoccer.tools.HttpHelper.java
public static int getStatusCode(String url, int timeout) throws IOException { HttpHead head = new HttpHead(url); try {/*from w ww . j ava 2s. c om*/ HttpResponse response = executeHTTPMethod(head, timeout); return response.getStatusLine().getStatusCode(); } catch (HttpException ex) { return ex.getStatusCode(); } }
From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java
private HttpResponse head(CloseableHttpClient httpClient, String uri, int expectedCode) throws Exception { HttpResponse response;//from w w w .j a v a2 s . co m HttpHead head = new HttpHead(uri); response = httpClient.execute(head); assertEquals(expectedCode, response.getStatusLine().getStatusCode()); return response; }
From source file:org.opencastproject.distribution.hls.HLSDistributionServiceImpl.java
/** * Distribute a Mediapackage element to the hls distribution service. * /* w ww .j av a2 s .c o m*/ * @param mediapackage * The media package that contains the element to distribute. * @param elementId * The id of the element that should be distributed contained within the media package. * @param checkAvailability * Check the availability of the distributed element via http. * @return A reference to the MediaPackageElement that has been distributed. * @throws DistributionException * Thrown if the parent directory of the MediaPackageElement cannot be created, if the MediaPackageElement * cannot be copied or another unexpected exception occurs. */ public MediaPackageElement distributeElement(MediaPackage mediapackage, String elementId, boolean checkAvailability) throws DistributionException { if (mediapackage == null) throw new IllegalArgumentException("Mediapackage must be specified"); if (elementId == null) throw new IllegalArgumentException("Element ID must be specified"); String mediaPackageId = mediapackage.getIdentifier().compact(); MediaPackageElement element = mediapackage.getElementById(elementId); // Make sure the element exists if (mediapackage.getElementById(elementId) == null) throw new IllegalStateException("No element " + elementId + " found in mediapackage"); try { File source; try { source = workspace.get(element.getURI()); } catch (NotFoundException e) { throw new DistributionException("Unable to find " + element.getURI() + " in the workspace", e); } catch (IOException e) { throw new DistributionException("Error loading " + element.getURI() + " from the workspace", e); } File destination = getDistributionFile(mediapackage, element); // Create directories for distributed files try { FileUtils.forceMkdir(destination.getParentFile()); } catch (IOException e) { throw new DistributionException("Unable to create " + destination.getParentFile(), e); } logger.info("Distributing {} to {}", elementId, destination); //TODO segment the file into place using ffmpeg // try { // FileSupport.link(source, destination, true); // } catch (IOException e) { // throw new DistributionException("Unable to copy " + source + " to " + destination, e); // } // Create a representation of the distributed file in the mediapackage MediaPackageElement distributedElement = (MediaPackageElement) element.clone(); try { distributedElement.setURI(getDistributionUri(mediaPackageId, element)); } catch (URISyntaxException e) { throw new DistributionException("Distributed element produces an invalid URI", e); } distributedElement.setIdentifier(null); logger.info("Finished distribution of {}", element); URI uri = distributedElement.getURI(); long now = 0L; while (checkAvailability) { HttpResponse response = trustedHttpClient.execute(new HttpHead(uri)); if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) break; if (now < TIMEOUT) { try { Thread.sleep(INTERVAL); now += INTERVAL; continue; } catch (Exception e) { throw new RuntimeException(e); } } logger.warn("Status code of distributed file {}: {}", uri, response.getStatusLine().getStatusCode()); throw new DistributionException("Unable to load distributed file " + uri.toString()); } return distributedElement; } catch (Exception e) { logger.warn("Error distributing " + element, e); if (e instanceof DistributionException) { throw (DistributionException) e; } else { throw new DistributionException(e); } } }
From source file:org.wrml.core.www.WebClient.java
private Message sendRequestMessage(Message requestMessage) { HttpUriRequest request = null;/*from www . j a v a 2s .c o m*/ final RequestLine requestLine = (RequestLine) requestMessage.getStartLine(); final Method method = requestLine.getMethod(); final URI uri = requestLine.getUri(); switch (method) { case GET: request = new HttpGet(uri); break; case HEAD: request = new HttpHead(uri); break; case POST: request = new HttpPost(uri); break; case PUT: request = new HttpPut(uri); break; case DELETE: request = new HttpDelete(uri); break; case OPTIONS: request = new HttpOptions(uri); break; case TRACE: request = new HttpTrace(uri); break; case CONNECT: default: break; } InputStream inputStream = null; MediaType responseMediaType = null; try { final HttpResponse response = _HttpClient.execute(request); final HttpEntity entity = response.getEntity(); final Transformers<String> stringTransformers = getContext().getStringTransformers(); responseMediaType = stringTransformers.getTransformer(MediaType.class) .bToA(entity.getContentType().getValue()); if (entity != null) { inputStream = entity.getContent(); } } catch (final ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } final StatusLine statusLine = new DefaultStatusLine(); // TODO: Implement transformers for the string values to enums //statusLine.setHTTPVersion(httpVersion); //statusLine.setStatus(status); // Create the response message final Message responseMessage = createMessage(MessageType.RESPONSE, statusLine); final Entity responseEntity = responseMessage.getEntity(); responseEntity.getHeaders().setContentType(responseMediaType); responseEntity.getBody().setInputStream(inputStream); return responseMessage; }
From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java
private org.apache.http.HttpRequest buildHttpUriRequest(HttpRequest request, Joiner joiner, URI requestUri) { org.apache.http.HttpRequest httpRequest; if (autoEncodeUri) { switch (request.getHttpMethod()) { case GET: httpRequest = new HttpGet(requestUri); break; case POST: httpRequest = new HttpPost(requestUri); break; case PUT: httpRequest = new HttpPut(requestUri); break; case DELETE: httpRequest = new HttpDelete(requestUri); break; case HEAD: httpRequest = new HttpHead(requestUri); break; case OPTIONS: httpRequest = new HttpOptions(requestUri); break; case PATCH: httpRequest = new HttpPatch(requestUri); break; default:/*from w ww . j av a 2 s . co m*/ throw new ClientException("You have to one of the REST verbs such as GET, POST etc."); } } else { switch (request.getHttpMethod()) { case POST: case PUT: case DELETE: case PATCH: httpRequest = new BasicHttpEntityEnclosingRequest(request.getHttpMethod().method(), requestUri.toString()); break; default: httpRequest = new BasicHttpRequest(request.getHttpMethod().method(), requestUri.toString()); } } byte[] entity = request.getEntity(); if (entity != null) { if (httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest; httpEntityEnclosingRequestBase .setEntity(new ByteArrayEntity(entity, ContentType.create(request.getContentType()))); } else { throw new ClientException( "sending content for request type " + request.getHttpMethod() + " is not supported!"); } } else { if (request instanceof ApacheHttpRequest && httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest; ApacheHttpRequest apacheHttpRequest = (ApacheHttpRequest) request; httpEntityEnclosingRequestBase.setEntity(apacheHttpRequest.getApacheHttpEntity()); } } Map<String, Collection<String>> headers = request.getHeaders(); for (Map.Entry<String, Collection<String>> stringCollectionEntry : headers.entrySet()) { String key = stringCollectionEntry.getKey(); Collection<String> stringCollection = stringCollectionEntry.getValue(); String value = joiner.join(stringCollection); httpRequest.setHeader(key, value); } return httpRequest; }
From source file:com.fhc25.percepcion.osiris.mapviewer.common.restutils.RestClient.java
/** * Executes the requests.//from w ww. ja v a 2 s . c om * * @param method the type of method (POST, GET, DELETE, PUT). * @param url the url of the request. * @param headers the headers to include. * @param params the params to include (if any) * @param listener a listener for callbacks. * @throws Exception */ public static void Execute(final RequestMethod method, final String url, final List<NameValuePair> headers, final List<NameValuePair> params, final RestListener listener) throws Exception { new Thread() { @Override public void run() { switch (method) { case GET: { // add parameters String combinedParams = ""; if (params != null) { if (!params.isEmpty()) { combinedParams += "?"; } for (NameValuePair p : params) { String paramString = ""; try { paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), HTTP.DEFAULT_CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (combinedParams.length() > 1) combinedParams += "&" + paramString; else combinedParams += paramString; } } HttpGet request = new HttpGet(url + combinedParams); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url, listener); break; } case POST: { HttpPost request = new HttpPost(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } if (params != null) { try { if (params.get(0).getName() == "json") { se = new StringEntity(params.get(0).getValue(), HTTP.UTF_8); //se.setContentEncoding( HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending json parameter: " + params.get(0).getValue()); if (se != null) { Lgr.v(TAG, "Entity string: " + se.toString()); if (se.getContentEncoding() != null) { Lgr.v(TAG, "Entity encoding: " + request.getEntity().getContentEncoding().getValue()); } } } else if (params.get(0).getName() == "xml") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending xml parameter: " + params.get(0).getValue()); } else { request.setEntity(new UrlEncodedFormEntity(params, HTTP.DEFAULT_CONTENT_CHARSET)); Lgr.v(TAG, "Sending UrlEncodedForm parameters "); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Lgr.v(TAG, "Request " + request.toString()); executeRequest(request, url, listener); break; } case PUT: { HttpPut request = new HttpPut(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } if (params != null) { try { if (params.get(0).getName() == "json") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending json parameter: " + params.get(0).getValue()); } else if (params.get(0).getName() == "xml") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending xml parameter: " + params.get(0).getValue()); } else if (params.get(0).getName() == "string") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending string parameter: " + params.get(0).getValue()); } else { request.setEntity(new UrlEncodedFormEntity(params, HTTP.DEFAULT_CONTENT_CHARSET)); Lgr.v(TAG, "Sending UrlEncodedForm parameters "); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Lgr.v(TAG, "Request " + request.toString()); executeRequest(request, url, listener); break; } case PATCH: { HttpPatch request = new HttpPatch(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } if (params != null) { try { if (params.get(0).getName() == "json") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending json parameter: " + params.get(0).getValue()); } else if (params.get(0).getName() == "xml") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending xml parameter: " + params.get(0).getValue()); } else if (params.get(0).getName() == "string") { se = new StringEntity(params.get(0).getValue(), HTTP.DEFAULT_CONTENT_CHARSET); request.setEntity(se); Lgr.v(TAG, "Sending string parameter: " + params.get(0).getValue()); } else { request.setEntity(new UrlEncodedFormEntity(params, HTTP.DEFAULT_CONTENT_CHARSET)); Lgr.v(TAG, "Sending UrlEncodedForm parameters "); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } Lgr.v(TAG, "Request " + request.toString()); executeRequest(request, url, listener); break; } case HEAD: { HttpHead request = new HttpHead(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } Lgr.v(TAG, "Request " + request.toString()); executeRequest(request, url, listener); break; } case DELETE: { HttpDelete request = new HttpDelete(url); // add headers if (headers != null) { for (NameValuePair h : headers) request.addHeader(h.getName(), h.getValue()); } executeRequest(request, url, listener); break; } } } }.start(); }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException { try {//from w w w. j a v a2 s . c o m CloseableHttpClient httpclient = HttpClientProperties.createHttpClient(); try { // Read content of config pipe Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG); Node configNode = configDocument.selectSingleNode("//config"); URL theURL = new URL(configNode.valueOf("url")); if (configNode.valueOf("auth-method").equals("basic")) { HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol()); //Authentication support CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configNode.valueOf("username"), configNode.valueOf("password"))); // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context httpContext = HttpClientContext.create(); httpContext.setCredentialsProvider(credsProvider); httpContext.setAuthCache(authCache); } else if (configNode.valueOf("auth-method").equals("form")) { //Sign in. Cookie will be remembered bij httpclient HttpPost authpost = new HttpPost(configNode.valueOf("auth-url")); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username"))); nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password"))); authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse httpResponse = httpclient.execute(authpost); // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode())); } CloseableHttpResponse response; if (configNode.valueOf("method").equals("post")) { // POST HttpPost httpRequest = new HttpPost(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("put")) { // PUT HttpPut httpRequest = new HttpPut(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("delete")) { //DELETE HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("head")) { //HEAD HttpHead httpRequest = new HttpHead(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("options")) { //OPTIONS HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else { //Default = GET HttpGet httpRequest = new HttpGet(configNode.valueOf("url")); String acceptHeader = configNode.valueOf("accept"); if (!acceptHeader.isEmpty()) { httpRequest.addHeader("accept", configNode.valueOf("accept")); } //Add proxy route if needed HttpClientProperties.setProxy(httpRequest, theURL.getHost()); response = executeRequest(httpRequest, httpclient); } try { contentHandler.startDocument(); int status = response.getStatusLine().getStatusCode(); AttributesImpl statusAttr = new AttributesImpl(); statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status)); contentHandler.startElement("", "response", "response", statusAttr); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); Header contentType = response.getFirstHeader("Content-Type"); if (entity != null && contentType != null) { //logger.info("Contenttype: " + contentType.getValue()); //Read content into inputstream InputStream inStream = entity.getContent(); // output-type = json means: response is json, convert to xml if (configNode.valueOf("output-type").equals("json")) { //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!! //javax.json contains readers to read from an inputstream StringWriter writer = new StringWriter(); IOUtils.copy(inStream, writer, "UTF-8"); JSONObject json = JSONObject.fromObject(writer.toString()); parseJSONObject(contentHandler, json); // output-type = xml means: response is xml, keep it } else if (configNode.valueOf("output-type").equals("xml")) { try { XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml } else if (configNode.valueOf("output-type").equals("jsonld")) { try { Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response! Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback()); Any23 runner = new Any23(); DocumentSource source = new StringDocumentSource((String) nquads, configNode.valueOf("url")); ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inJsonStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml } else if (configNode.valueOf("output-type").equals("rdf")) { try { Any23 runner = new Any23(); DocumentSource source; //If contentType = text/html than convert from html to xhtml to handle non-xml style html! logger.info("Contenttype: " + contentType.getValue()); if (configNode.valueOf("tidy").equals("yes") && contentType.getValue().startsWith("text/html")) { org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8", configNode.valueOf("url")); //TODO UTF-8 should be read from response! RDFCleaner cleaner = new RDFCleaner(); org.jsoup.nodes.Document cleandoc = cleaner.clean(doc); cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); cleandoc.outputSettings() .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); cleandoc.outputSettings().charset("UTF-8"); source = new StringDocumentSource(cleandoc.html(), configNode.valueOf("url"), contentType.getValue()); } else { source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"), contentType.getValue()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inAnyStream)); } catch (Exception e) { throw new OXFException(e); } } else { CharArrayWriter writer = new CharArrayWriter(); IOUtils.copy(inStream, writer, "UTF-8"); contentHandler.characters(writer.toCharArray(), 0, writer.size()); } } } contentHandler.endElement("", "response", "response"); contentHandler.endDocument(); } finally { response.close(); } } finally { httpclient.close(); } } catch (Exception e) { throw new OXFException(e); } }
From source file:org.switchyard.component.http.OutboundHandler.java
/** * The handler method that invokes the actual HTTP service when the * component is used as a HTTP consumer. * @param exchange the Exchange/*from w w w . j av a 2 s.co m*/ * @throws HandlerException handler exception */ @Override public void handleMessage(final Exchange exchange) throws HandlerException { // identify ourselves exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) .addLabels(BehaviorLabel.TRANSIENT.label()); if (getState() != State.STARTED) { final String m = HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName); LOGGER.error(m); throw new HandlerException(m); } HttpClient httpclient = new DefaultHttpClient(); if (_timeout != null) { HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, _timeout); HttpConnectionParams.setSoTimeout(httpParams, _timeout); } try { if (_credentials != null) { ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); authpref.add(AuthPolicy.BASIC); httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); } if (_proxyHost != null) { httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost); } HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData()); HttpRequestBase request = null; if (_httpMethod.equals(HTTP_GET)) { request = new HttpGet(_baseAddress); } else if (_httpMethod.equals(HTTP_POST)) { request = new HttpPost(_baseAddress); ((HttpPost) request).setEntity(new BufferedHttpEntity( new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available()))); } else if (_httpMethod.equals(HTTP_DELETE)) { request = new HttpDelete(_baseAddress); } else if (_httpMethod.equals(HTTP_HEAD)) { request = new HttpHead(_baseAddress); } else if (_httpMethod.equals(HTTP_PUT)) { request = new HttpPut(_baseAddress); ((HttpPut) request).setEntity(new BufferedHttpEntity( new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available()))); } else if (_httpMethod.equals(HTTP_OPTIONS)) { request = new HttpOptions(_baseAddress); } Iterator<Map.Entry<String, List<String>>> entries = httpRequest.getHeaders().entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, List<String>> entry = entries.next(); String name = entry.getKey(); if (REQUEST_HEADER_BLACKLIST.contains(name)) { HttpLogger.ROOT_LOGGER.removingProhibitedRequestHeader(name); continue; } List<String> values = entry.getValue(); for (String value : values) { request.addHeader(name, value); } } if (_contentType != null) { request.addHeader("Content-Type", _contentType); } HttpResponse response = null; if ((_credentials != null) && (_credentials instanceof NTCredentials)) { // Send a request for the Negotiation response = httpclient.execute(new HttpGet(_baseAddress)); HttpClientUtils.closeQuietly(response); } if (_authCache != null) { BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, _authCache); response = httpclient.execute(request, context); } else { response = httpclient.execute(request); } int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); HttpResponseBindingData httpResponse = new HttpResponseBindingData(); Header[] headers = response.getAllHeaders(); for (Header header : headers) { httpResponse.addHeader(header.getName(), header.getValue()); } if (entity != null) { if (entity.getContentType() != null) { httpResponse.setContentType(new ContentType(entity.getContentType().getValue())); } else { httpResponse.setContentType(new ContentType()); } httpResponse.setBodyFromStream(entity.getContent()); } httpResponse.setStatus(status); Message out = _messageComposer.compose(httpResponse, exchange); if (httpResponse.getStatus() < 400) { exchange.send(out); } else { exchange.sendFault(out); } } catch (Exception e) { final String m = HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage(); LOGGER.error(m, e); throw new HandlerException(m, e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.ibm.ws.lars.rest.RepositoryContext.java
public HttpResponse doHead(String url, int expectedStatusCode) throws ClientProtocolException, IOException { HttpHead head = new HttpHead(fullURL + url); HttpResponse response = httpClient.execute(targetHost, head, context); assertStatusCode(expectedStatusCode, response); return response; }