List of usage examples for org.apache.commons.httpclient HttpMethod getStatusText
public abstract String getStatusText();
From source file:com.intuit.tank.http.BaseRequest.java
public void sendRequest(BaseResponse response, @Nonnull HttpMethod method, String requestBody) { String uri = null;/*from w ww .j a va2 s. c om*/ long waitTime = 0L; try { this.response = response; uri = method.getURI().toString(); logger.debug( LogUtil.getLogMessage("About to POST request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); logRequest(uri, requestBody, method.getName(), headerInformation, httpclient, false); BaseRequestHandler.setHeaders(method, headerInformation); long startTime = System.currentTimeMillis(); timestamp = new Date(startTime); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); BaseRequestHandler.processResponse(responseBody, startTime, endTime, response, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(LogUtil.getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { method.releaseConnection(); } if (waitTime != 0) { doWaitDueToLongResponse(waitTime, uri); } }
From source file:com.zimbra.cs.service.UserServlet.java
private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method) throws ServiceException { // create an HTTP client with the same cookies String url = ""; String hostname = ""; try {/*from w w w.ja v a 2 s .com*/ url = method.getURI().toString(); hostname = method.getURI().getHost(); } catch (IOException e) { log.warn("can't parse target URI", e); } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); Map<String, String> cookieMap = authToken.cookieMap(false); if (cookieMap != null) { HttpState state = new HttpState(); for (Map.Entry<String, String> ck : cookieMap.entrySet()) { state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/", null, false)); } client.setState(state); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (method instanceof PutMethod) { long contentLength = ((PutMethod) method).getRequestEntity().getContentLength(); if (contentLength > 0) { int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis // cannot set connection time using our ZimbrahttpConnectionManager, // see comments in ZimbrahttpConnectionManager. // actually, length of the content to Put should not be a factor for // establishing a connection, only read time out matter, which we set // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate); method.getParams().setSoTimeout(timeEstimate); } } try { int statusCode = HttpClientUtil.executeMethod(client, method); if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN) throw MailServiceException.NO_SUCH_ITEM(-1); else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null, new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR), new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode, ServiceException.Argument.Type.NUM)); List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders())); headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode)); return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method); } catch (HttpException e) { throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e); } catch (IOException e) { throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e); } }
From source file:com.intuit.tank.httpclient3.TankHttpClient3.java
private void sendRequest(BaseRequest request, @Nonnull HttpMethod method, String requestBody) { String uri = null;// w w w .java 2s. com long waitTime = 0L; try { uri = method.getURI().toString(); logger.debug(request.getLogUtil().getLogMessage( "About to " + method.getName() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); List<String> cookies = new ArrayList<String>(); if (httpclient != null && httpclient.getState() != null && httpclient.getState().getCookies() != null) { for (Cookie cookie : httpclient.getState().getCookies()) { cookies.add("REQUEST COOKIE: " + cookie.toExternalForm() + " (domain=" + cookie.getDomain() + " : path=" + cookie.getPath() + ")"); } } request.logRequest(uri, requestBody, method.getName(), request.getHeaderInformation(), cookies, false); setHeaders(request, method, request.getHeaderInformation()); long startTime = System.currentTimeMillis(); request.setTimestamp(new Date(startTime)); httpclient.executeMethod(method); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) { try { InputStream httpInputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int curByte = httpInputStream.read(); while (curByte >= 0) { out.write(curByte); curByte = httpInputStream.read(); } responseBody = out.toByteArray(); } catch (Exception e) { logger.warn("could not get response body: " + e); } } long endTime = System.currentTimeMillis(); processResponse(responseBody, startTime, endTime, request, method.getStatusText(), method.getStatusCode(), method.getResponseHeaders(), httpclient.getState()); waitTime = endTime - startTime; } catch (Exception ex) { logger.error(request.getLogUtil().getLogMessage( "Could not do " + method.getName() + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { try { method.releaseConnection(); } catch (Exception e) { logger.warn("Could not release connection: " + e, e); } if (method.getName().equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { logger.info(request.getLogUtil() .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } }
From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java
/** * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer) *//*from w w w . j a v a2s .com*/ @Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { logger.debug("BEGIN perform(GVBuffer gvBuffer)"); HttpMethod method = null; try { String currMethodURI = null; Map<String, Object> params = GVBufferPropertiesHelper.getPropertiesMapSO(gvBuffer, true); String currHost = PropertiesHandler.expand(host, params, gvBuffer); String currPort = PropertiesHandler.expand(port, params, gvBuffer); logger.debug("Server Host: " + currHost + " - Port: " + currPort); httpClient.getHostConfiguration().setHost(currHost, Integer.parseInt(currPort), protocol); auth.setAuthentication(httpClient, host, Integer.parseInt(currPort), gvBuffer, params); proxy.setProxy(httpClient, gvBuffer, params); currMethodURI = PropertiesHandler.expand(contextPath + methodURI, params, gvBuffer); logger.debug("MethodURI[escaped:" + uriEscaped + "]=[" + currMethodURI + "]"); switch (methodName) { case OPTIONS: method = new OptionsMethod(); break; case GET: method = new GetMethod(); break; case HEAD: method = new HeadMethod(); break; case POST: method = new PostMethod(); break; case PUT: method = new PutMethod(); break; case DELETE: method = new DeleteMethod(); break; default: throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "id", gvBuffer.getId().toString() }, { "message", "Unknown method = " + methodName } }); } method.setURI(new URI(currMethodURI, uriEscaped)); if ((refDP != null) && (refDP.length() > 0)) { logger.debug("Calling configured Data Provider: " + refDP); DataProviderManager dataProviderManager = DataProviderManager.instance(); IDataProvider dataProvider = dataProviderManager.getDataProvider(refDP); try { dataProvider.setContext(method); dataProvider.setObject(gvBuffer); method = (HttpMethod) dataProvider.getResult(); } finally { dataProviderManager.releaseDataProvider(refDP, dataProvider); } } int status = httpClient.executeMethod(method); gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(status)); String statusTxt = method.getStatusText(); gvBuffer.setProperty(RESPONSE_MESSAGE, (statusTxt != null ? statusTxt : "NULL")); Header[] responseHeaders = method.getResponseHeaders(); for (Header header : responseHeaders) { String headerName = RESPONSE_HEADER_PREFIX + header.getName(); String value = header.getValue(); if (value == null) { value = ""; } gvBuffer.setProperty(headerName, value); } String cType = "text/html"; Header cTypeHeader = method.getResponseHeader("Content-Type"); if (cTypeHeader != null) { String cTypeValue = cTypeHeader.getValue(); if (cTypeValue != null) { cType = cTypeValue; } } logger.debug("Response content-type: " + cType); ContentType contentType = new ContentType(cType); byte[] responseBody = method.getResponseBody(); Object object = responseBody; if (contentType.getPrimaryType().equals("multipart")) { object = handleMultipart(responseBody, cType); } gvBuffer.setObject(object); } catch (CallException exc) { throw exc; } catch (Exception exc) { logger.error("ERROR perform(GVBuffer gvBuffer)", exc); throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "id", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception exc) { logger.warn("Error while releasing connection", exc); } logger.debug("END perform(GVBuffer gvBuffer)"); } return gvBuffer; }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
private byte[] executeMethod(HttpMethod method, final Context context) throws IOException, URIException, MalformedURLException, EngineException { Header[] requestHeaders, responseHeaders = null; byte[] result = null; String contents = null;/*from www . j a v a2s .c o m*/ int statuscode = -1; if (!context.requestedObject.runningThread.bContinue) return null; Engine.logBeans .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")"); try { requestHeaders = method.getRequestHeaders(); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString()); statuscode = doExecuteMethod(method, context); Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString()); responseHeaders = method.getResponseHeaders(); context.setResponseHeaders(responseHeaders); if (Engine.logBeans.isTraceEnabled()) Engine.logBeans .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString()); if (statuscode != -1) { InputStream in = method.getResponseBodyAsStream(); if (in != null) { /** * Retrieve response charset if available in responseHeaders */ charset = null; boolean checkGZip = false; // add GZip support #320 for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) { Header head = responseHeaders[i]; if (HeaderName.ContentType.is(head)) { context.contentType = head.getValue(); HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length && charset == null; j++) { NameValuePair nvp = els[j].getParameterByName("charset"); if (nvp != null) charset = nvp.getValue(); } } else if (HeaderName.ContentEncoding.is(head)) { checkGZip = true; HeaderElement[] els = head.getElements(); for (int j = 0; j < els.length; j++) if ("gzip".equals(els[j].getName())) { Engine.logBeans.debug("(HttpConnector) Decode GZip stream"); in = new GZIPInputStream(in); } } } if (context.contentType != null && context.contentType.startsWith("multipart/") && context.requestedObject instanceof AbstractHttpTransaction) { Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType"); try { AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in), context.contentType); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mp.nextPart(bos); result = bos.toByteArray(); if (transaction.getAllowDownloadAttachment()) { Document doc = context.outputDocument; Element attInfo = null; File file = File.createTempFile("c8o_", ".part"); for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) { try { file.deleteOnExit(); if (attInfo == null) { Engine.logBeans.debug("(HttpConnector) Saving attachment(s)"); attInfo = doc.createElement("AttachmentInfo"); doc.getDocumentElement().appendChild(attInfo); } Element att = doc.createElement("attachment"); attInfo.appendChild(att); String cid = bp.getContentID(); if (cid != null) { cid = cid.replaceFirst("^<?(.*?)>?$", "$1"); att.setAttribute("cid", "cid:" + cid); } Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid + " in file: " + file.getAbsolutePath()); att.setAttribute("filepath", file.getAbsolutePath()); Enumeration<javax.mail.Header> headers = GenericUtils .cast(bp.getAllHeaders()); while (headers.hasMoreElements()) { javax.mail.Header header = headers.nextElement(); Element eHeader = doc.createElement("header"); att.appendChild(eHeader); eHeader.setAttribute("name", header.getName()); eHeader.setAttribute("value", header.getValue()); } } catch (Exception e1) { Engine.logBeans .error("(HttpConnector) Failed to retrieve the attachment in " + file.getAbsolutePath(), e1); } file = File.createTempFile("c8o_", ".part"); } file.delete(); in.close(); } } catch (Exception e) { Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e); } } else { result = IOUtils.toByteArray(in); in.close(); } } if (Engine.logBeans.isTraceEnabled()) { contents = new String((result != null) ? result : new byte[] {}); Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents); } String redirectUrl, newuri; GetMethod redirectMethod = null; // Handles REDIRECTION through Location header if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header location = method.getResponseHeader("Location"); if (location != null) { newuri = location.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } // ignore any data after the ";" character int split = newuri.indexOf(';'); if (split != -1) { newuri = newuri.substring(0, split); } redirectUrl = getAbsoluteUrl(method, newuri); Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl); redirectMethod = new GetMethod(redirectUrl); // set headers for (int i = 0; i < requestHeaders.length; i++) redirectMethod.setRequestHeader(requestHeaders[i]); referer = redirectUrl.startsWith("http") ? redirectUrl : (hostConfiguration.getHostURL() + redirectUrl); result = executeMethod(redirectMethod, context); // recurse } else { Engine.logBeans.debug("(HttpConnector) Invalid redirect!"); } } else { /* * String lwContents = contents.toLowerCase(); int index, i, * j, k, z; // Handles REDIRECTION through META Refresh if * (((index = lwContents.indexOf("http-equiv='refresh'")) != * -1) || ((index = * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) { * if ((i = lwContents.indexOf("content=", index + 20)) != * -1) { char c = lwContents.charAt(i+8); if ((j = * lwContents.indexOf("url=", i)) != -1) { if ((k = * lwContents.indexOf(c, j + 1)) != -1) { newuri = * lwContents.substring(j+4, k); redirectUrl = * getAbsoluteUrl(method,newuri); * Engine.logBeans.debug("(HttpConnector) Redirecting to : " * + redirectUrl); redirectMethod = new * GetMethod(redirectUrl); * * // set headers for (z=0; z<requestHeaders.length; z++) * redirectMethod.setRequestHeader(requestHeaders[z]); * * referer = redirectUrl; result = * executeMethod(redirectMethod, context); // recurse } } } * } // Handles FRAMESET else if * (lwContents.indexOf("frameset") != -1) { * Engine.logBeans.debug * ("(HttpConnector) Analyzing frameset..."); * StringTokenizer st = new StringTokenizer(lwContents); * StringEx newcontents = new StringEx(lwContents); while * (st.hasMoreTokens()) { String token = st.nextToken(); * String uri; if (token.startsWith("src=")) { if * ((token.indexOf("\"") != -1) || (token.indexOf("'") != * -1)) { token = token.substring(5); uri = * token.substring(0,token.length()-1); newuri = * getAbsoluteUrl(method,uri); * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+ * uri +") with newuri("+ newuri +")"); * * newcontents.replaceAll(token,newuri); } } } * Engine.logBeans * .trace("(HttpConnector) New response content:\n"+ * newcontents); result = newcontents.toString().getBytes(); * } */ } } //Added by julienda - #3433 - 04/03/2013 AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction; if (abstractHttpTransaction.getHttpInfo()) { Document doc = context.outputDocument; //Remove the node HTTPInfo if we have a redirect NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(), abstractHttpTransaction.getHttpInfoTagName()); if (nodeList != null) { XMLUtils.removeNodeListContent(nodeList); } //Parent Element httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName()); //Add requested URL Element urlElement = doc.createElement("url"); urlElement.setTextContent(method.getURI().toString()); httpInfoElement.appendChild(urlElement); //Add status code Element httpStatusElement = doc.createElement("status"); httpStatusElement.setAttribute("code", Integer.toString(statuscode)); httpStatusElement.setAttribute("text", method.getStatusText()); httpInfoElement.appendChild(httpStatusElement); //We add headers informations List<Header> headers = Arrays.asList(requestHeaders); if (!headers.isEmpty()) { Element httpHeadersElement = doc.createElement("headers"); for (int i = 0; i < headers.size(); i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", headers.get(i).getName()); elt.setAttribute("value", headers.get(i).getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } // we add response header information if (responseHeaders.length != 0) { Element httpHeadersElement = doc.createElement("responseHeaders"); for (int i = 0; i < responseHeaders.length; i++) { Element elt = doc.createElement("header"); elt.setAttribute("name", responseHeaders[i].getName()); elt.setAttribute("value", responseHeaders[i].getValue()); httpHeadersElement.appendChild(elt); } httpInfoElement.appendChild(httpHeadersElement); } doc.getDocumentElement().appendChild(httpInfoElement); } } finally { method.releaseConnection(); } return result; }
From source file:nl.nn.adapterframework.http.HttpSender.java
public String extractResult(HttpMethod httpmethod, ParameterResolutionContext prc, HttpServletResponse response, String fileName) throws SenderException, IOException { int statusCode = httpmethod.getStatusCode(); boolean ok = false; if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey())) { prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode)); ok = true;//from w ww .j a va 2s. c o m } else { if (statusCode == HttpServletResponse.SC_OK) { ok = true; } else { if (isIgnoreRedirects()) { if (statusCode == HttpServletResponse.SC_MOVED_PERMANENTLY || statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) { ok = true; } } } } if (!ok) { throw new SenderException(getLogPrefix() + "httpstatus " + statusCode + ": " + httpmethod.getStatusText() + " body: " + getResponseBodyAsString(httpmethod)); } if (response == null) { if (fileName == null) { if (isBase64()) { return getResponseBodyAsBase64(httpmethod); } else if (StringUtils.isNotEmpty(getStoreResultAsStreamInSessionKey())) { prc.getSession().put(getStoreResultAsStreamInSessionKey(), new ReleaseConnectionAfterReadInputStream(httpmethod, httpmethod.getResponseBodyAsStream())); return ""; } else if (StringUtils.isNotEmpty(getStoreResultAsByteArrayInSessionKey())) { InputStream is = httpmethod.getResponseBodyAsStream(); prc.getSession().put(getStoreResultAsByteArrayInSessionKey(), IOUtils.toByteArray(is)); return ""; } else if (isMultipartResponse()) { return handleMultipartResponse(httpmethod.getResponseHeader("Content-Type").getValue(), httpmethod.getResponseBodyAsStream(), prc, httpmethod); } else { //return httpmethod.getResponseBodyAsString(); return getResponseBodyAsString(httpmethod); } } else { InputStream is = httpmethod.getResponseBodyAsStream(); File file = new File(fileName); Misc.streamToFile(is, file); return fileName; } } else { streamResponseBody(httpmethod, response); return ""; } }
From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java
/** * Debugging method for obtaining the state of a response as a String. * /* w w w .jav a2 s. c o m*/ * @param method The method to retrieve the response state from <i>(may be null)</i>. * @return The response state as a human-readable string value <i>(will not be null)</i>. */ private String responseToString(final HttpMethod method) { StringBuffer result = new StringBuffer(128); if (method != null) { result.append("\n\tStatus: "); result.append(method.getStatusCode()); result.append(" "); result.append(method.getStatusText()); result.append("\n\tHeaders: "); for (final Header header : method.getResponseHeaders()) { result.append("\n\t\t"); result.append(header.getName()); result.append(" : "); result.append(header.getValue()); } result.append("\n\tBody:"); result.append("\n"); try { result.append(method.getResponseBodyAsString()); } catch (final IOException ioe) { result.append("unknown, due to: " + ioe.getMessage()); } } else { result.append("(null)"); } return (result.toString()); }
From source file:org.alfresco.web.bean.ajax.PresenceProxyBean.java
/** * Perform request/* w ww .j av a 2 s . c o m*/ */ public String getUrlResponse(String requestUrl) { String response = ""; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(requestUrl); method.setRequestHeader("Accept", "*/*"); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { response = method.getResponseBodyAsString(); } else { response = method.getStatusText(); } } catch (HttpException e) { response = e.getMessage(); } catch (IOException e) { response = e.getMessage(); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:org.apache.cocoon.transformation.SparqlTransformer.java
private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters) throws ProcessingException, IOException, SAXException { HttpClient httpclient = new HttpClient(); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; }/* w w w .j a v a 2 s . co m*/ nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpclient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpclient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } // Make the HttpMethod. HttpMethod httpMethod = null; // Do not use empty query parameter. if (requestParameters.getParameter(parameterName).trim().equals("")) { requestParameters.removeParameter(parameterName); } // Instantiate different HTTP methods. if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(url); if (requestParameters.getEncodedQueryString() != null) { httpMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpMethod.setQueryString(""); } } else if ("POST".equalsIgnoreCase(method)) { PostMethod httpPostMethod = new PostMethod(url); if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE)) .startsWith("application/x-www-form-urlencoded")) { // Encode parameters in POST body. Iterator parNames = requestParameters.getParameterNames(); while (parNames.hasNext()) { String parName = (String) parNames.next(); httpPostMethod.addParameter(parName, requestParameters.getParameter(parName)); } } else { // Use query parameter as POST body httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName)); // Add other parameters to query string requestParameters.removeParameter(parameterName); if (requestParameters.getEncodedQueryString() != null) { httpPostMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpPostMethod.setQueryString(""); } } httpMethod = httpPostMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod httpPutMethod = new PutMethod(url); httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName)); requestParameters.removeParameter(parameterName); httpPutMethod.setQueryString(requestParameters.getEncodedQueryString()); httpMethod = httpPutMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(url); httpMethod.setQueryString(requestParameters.getEncodedQueryString()); } else { throw new ProcessingException("Unsupported method: " + method); } // Authentication (optional). if (credentials != null && credentials.length() > 0) { String[] unpw = credentials.split("\t"); httpclient.getParams().setAuthenticationPreemptive(true); httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(unpw[0], unpw[1])); } // Add request headers. Iterator headers = httpHeaders.entrySet().iterator(); while (headers.hasNext()) { Map.Entry header = (Map.Entry) headers.next(); httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue()); } // Declare some variables before the try-block. XMLizer xmlizer = null; try { // Execute the request. int responseCode; responseCode = httpclient.executeMethod(httpMethod); // Handle errors, if any. if (responseCode < 200 || responseCode >= 300) { if (showErrors) { AttributesImpl attrs = new AttributesImpl(); attrs.addCDATAAttribute("status", "" + responseCode); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs); String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error"); return; // Not a nice, but quick and dirty way to end. } else { throw new ProcessingException("Received HTTP status code " + responseCode + " " + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString()); } } // Parse the response if (responseCode == 204) { // No content. String statusLine = httpMethod.getStatusLine().toString(); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else if (parse.equalsIgnoreCase("xml")) { InputStream responseBodyStream = httpMethod.getResponseBodyAsStream(); xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE); xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(), new IncludeXMLConsumer(xmlConsumer)); responseBodyStream.close(); } else if (parse.equalsIgnoreCase("text")) { xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); String responseBody = httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else { throw new ProcessingException("Unknown parse type: " + parse); } } catch (ServiceException e) { throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e); } finally { if (xmlizer != null) manager.release((Component) xmlizer); httpMethod.releaseConnection(); } }
From source file:org.apache.hadoop.hbase.stargate.client.Client.java
/** * Execute a transaction method given a complete URI. * @param method the transaction method//ww w . ja v a2 s . c o m * @param headers HTTP header values to send * @param uri the URI * @return the HTTP response code * @throws IOException */ @SuppressWarnings("deprecation") public int executeURI(HttpMethod method, Header[] headers, String uri) throws IOException { method.setURI(new URI(uri)); if (headers != null) { for (Header header : headers) { method.addRequestHeader(header); } } long startTime = System.currentTimeMillis(); int code = httpClient.executeMethod(method); long endTime = System.currentTimeMillis(); if (LOG.isDebugEnabled()) { LOG.debug(method.getName() + " " + uri + ": " + code + " " + method.getStatusText() + " in " + (endTime - startTime) + " ms"); } return code; }