List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeaders
public abstract Header[] getResponseHeaders();
From source file:com.intuit.tank.httpclient3.TankHttpClient3.java
private void sendRequest(BaseRequest request, @Nonnull HttpMethod method, String requestBody) { String uri = null;//from ww w . j ava 2 s. c o m 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: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 ww w . j a va2s . c om 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.groupon.odo.Proxy.java
/** * Execute a request//from w ww.j a v a 2 s.c o m * * @param httpMethodProxyRequest * @param httpServletRequest * @param httpServletResponse * @param history * @param outStream * @throws Exception */ private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws Exception { int intProxyResponseCode = 999; try { // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); ArrayList<String> headersToRemove = getRemoveHeaders(); httpClient.getParams().setSoTimeout(60000); httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove); intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); } catch (Exception e) { requestInformation.get().outputString = "TIMEOUT"; logRequestHistory(httpMethodProxyRequest, httpServletResponse, history); throw e; } logger.info("Response code: {}, {}", intProxyResponseCode, HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString())); if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); processRedirect(stringStatusCode, httpMethodProxyRequest, httpServletRequest, httpServletResponse); } else { // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // there is no data for a HTTP 304 if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); int intNextByte; // Collect all of the server data while ((intNextByte = bufferedInputStream.read()) != -1) { outStream.write(intNextByte); } } } }
From source file:com.zenkey.net.prowser.Tab.java
/************************************************************************** * Writes tracing information that traces the request/response activity. * /*from w w w .j a v a 2 s . co m*/ * @param traceLevel * Indicates how much trace info to produce. * @param traceStream * An output stream where trace statements will be written. * @param httpMethod * The HttpMethod object of the request. */ private static void writeTrace(int traceLevel, PrintStream traceStream, HttpMethod httpMethod) { try { if (traceLevel >= TRACE_URI) { // Show trace output of the request URI traceStream .println("-------------------------------------------------------------------------------"); traceStream.println(httpMethod.getURI() + "\n"); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP request line traceStream.println(httpMethod.getName() + " " + httpMethod.getPath() + (httpMethod.getQueryString() == null ? "" : "?" + httpMethod.getQueryString()) + " " + httpMethod.getParams().getVersion().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP request headers for (Header header : httpMethod.getRequestHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } // Show trace of request entity body if (httpMethod instanceof PostMethod) { NameValuePair[] parameters = ((PostMethod) httpMethod).getParameters(); if (parameters != null) { // StringBuffer parameterString = new StringBuffer(); // for (NameValuePair parameter : parameters) { // parameterString.append(parameter.getName() + "=" + parameter.getValue() + "&"); // } // parameterString.deleteCharAt(parameterString.length() - 1); String parameterString = new String( ((ByteArrayRequestEntity) ((PostMethod) httpMethod).getRequestEntity()) .getContent(), "UTF-8"); traceStream.println(" |"); traceStream.println(" +-- " + parameterString); } } traceStream.println(); } if (traceLevel >= TRACE_REQUEST_RESPONSE_LINES) { // Show trace output of the HTTP status line traceStream.println(httpMethod.getStatusLine().toString()); } if (traceLevel >= TRACE_HEADERS) { // Show trace output of the HTTP response headers for (Header header : httpMethod.getResponseHeaders()) { traceStream.println(header.getName() + ": " + header.getValue()); } traceStream.println(); } if (traceLevel >= TRACE_BODY) { // Show trace output of the HTTP response body traceStream.println(httpMethod.getResponseBodyAsString()); traceStream.println(); } } catch (Exception e) { e.printStackTrace(); } }
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;/*w w w. j av 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:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java
/** * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer) *///from w w w .ja va 2 s . c o m @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:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails// w w w . jav a 2s . co m * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } LOG.trace("Response has data? {}", !noData); if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @param digest /*from ww w. j a v a2s . co m*/ * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String user, String password) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient = new HttpClient(); if (user != null && password != null) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password); httpClient.getState().setCredentials(AuthScope.ANY, upc); } httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { // Skip GZIP Responses if (header.getName().equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING)) continue; else httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream(); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int read; while ((read = inputStreamServerResponse.read()) > 0) { if (escapeHtmlFull(read) > 0) { outputStreamClientResponse.write(read); } } inputStreamServerResponse.close(); outputStreamClientResponse.write('\n'); outputStreamClientResponse.flush(); outputStreamClientResponse.close(); }
From source file:freeciv.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred *///from ww w .jav a2s .co m private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setFollowRedirects(false); String port = "" + httpServletRequest.getSession().getAttribute("civserverport"); String host = "" + httpServletRequest.getSession().getAttribute("civserverhost"); String username = "" + httpServletRequest.getSession().getAttribute("username"); httpMethodProxyRequest.addRequestHeader("civserverport", port); httpMethodProxyRequest.addRequestHeader("civserverhost", host); httpMethodProxyRequest.addRequestHeader("username", username); int intProxyResponseCode = 0; // Execute the request try { intProxyResponseCode = client.executeMethod(httpMethodProxyRequest); } catch (IOException ioErr) { //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from. OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); httpServletResponse.setStatus(502); outputStreamClientResponse .write("Freeciv web client proxy not responding (most likely died).".getBytes()); httpMethodProxyRequest.releaseConnection(); return; } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { httpMethodProxyRequest.releaseConnection(); throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); httpMethodProxyRequest.releaseConnection(); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); httpMethodProxyRequest.releaseConnection(); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } httpMethodProxyRequest.releaseConnection(); }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred *//*from w ww .j a v a2s . c o m*/ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }