List of usage examples for java.net URLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:org.apache.jsp.communities_jsp.java
public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {/*from w ww. j a va2 s .c om*/ ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } }
From source file:org.apache.jsp.communities_jsp.java
private String postToRestfulApi(String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try {//from w w w .j ava 2 s.c o m URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { //System.out.println("Exception: " + e.getMessage()); } return result; }
From source file:org.apache.jsp.sources_jsp.java
public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try {//from ww w . ja v a 2s . c o m ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } }
From source file:org.apache.jsp.sources_jsp.java
private String postToRestfulApi(String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try {/* w w w . j a va2 s . c om*/ URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { //System.out.println("Exception: " + e.getMessage()); } return result; }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {//from w ww. jav a2 s . c om URL url = new URL(uri); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { URI uri = request.getURI();/* w w w .j a v a 2 s .c om*/ // Is this a CONNECT request? if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod())) { response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE???? handleConnect(pathInContext, pathParams, request, response); return; } try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) sendForbid(request, response, uri); return; } if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warn(e.toString()); LogSupport.ignore(log, e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request); } }
From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java
private ValidateResponse runHTTP(final X509Certificate cert) throws Exception { final URL processServlet = new URL(useSSL ? "https" : "http", hosts[0], port, servlet); OutputStream out = null;//from www . j a va 2 s . c om InputStream in = null; try { final URLConnection conn = processServlet.openConnection(); conn.setDoOutput(true); conn.setAllowUserInteraction(false); final StringBuilder sb = new StringBuilder(); sb.append("--" + BOUNDARY); sb.append(CRLF); try { final int workerId = Integer.parseInt(service); sb.append("Content-Disposition: form-data; name=\"workerId\""); sb.append(CRLF); sb.append(CRLF); sb.append(workerId); } catch (NumberFormatException e) { sb.append("Content-Disposition: form-data; name=\"workerName\""); sb.append(CRLF); sb.append(CRLF); sb.append(service); } sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"processType\""); sb.append(CRLF); sb.append(CRLF); sb.append("validateCertificate"); sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"datafile\""); sb.append("; filename=\""); sb.append(certPath.getAbsolutePath()); sb.append("\""); sb.append(CRLF); sb.append("Content-Type: application/octet-stream"); sb.append(CRLF); sb.append("Content-Transfer-Encoding: binary"); sb.append(CRLF); sb.append(CRLF); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = conn.getOutputStream(); out.write(sb.toString().getBytes()); out.write(cert.getEncoded()); out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); out.flush(); // Get the response in = conn.getInputStream(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); int len; final byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } os.close(); // read string from response final String response = os.toString(); final String[] responseParts = response.split(";"); // last part of the response string can by empty (revocation date) if (responseParts.length < 4 || responseParts.length > 5) { throw new IOException("Malformed HTTP response"); } final String revocationDateString = responseParts.length == 4 ? null : responseParts[4]; final Date revocationDate = revocationDateString != null && revocationDateString.length() > 0 ? new Date(Integer.valueOf(revocationDateString)) : null; final Validation validation = new Validation(cert, null, Validation.Status.valueOf(responseParts[0]), responseParts[2], revocationDate, Integer.valueOf(responseParts[3])); final ValidateResponse validateResponse = new ValidateResponse(validation, responseParts[1].split(",")); return validateResponse; } catch (IOException e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (in != null) { try { in.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }
From source file:org.lockss.proxy.ProxyHandler.java
/** Proxy a connection using Java's native URLConection */ void doSun(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { URI uri = request.getURI();//w w w .j av a 2 s.c o m try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) { sendForbid(request, response, uri); logAccess(request, "forbidden method: " + request.getMethod()); } return; } if (jlog.isDebugEnabled()) jlog.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean hasContent = false; Enumeration en = request.getFieldNames(); while (en.hasMoreElements()) { // XXX could be better than this! String hdr = (String) en.nextElement(); if (_DontProxyHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equalsIgnoreCase(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); } } } // Proxy headers connection.addRequestProperty(HttpFields.__Via, makeVia(request)); connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(jlog, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(jlog, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addField(HttpFields.__Via, makeVia(request)); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warning("doSun error", e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request, e.getMessage()); } }
From source file:org.openqa.selenium.server.ProxyHandler.java
protected long proxyPlainTextRequest(URL url, String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { CaptureNetworkTrafficCommand.Entry entry = new CaptureNetworkTrafficCommand.Entry(request.getMethod(), url.toString());// w ww .ja va 2 s. c o m entry.addRequestHeaders(request); if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); if (proxyInjectionMode) { adjustRequestForProxyInjection(request, connection); } // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); if (trustAllSSLCertificates && connection instanceof HttpsURLConnection) { TrustEverythingSSLTrustManager.trustAllSSLCertificates((HttpsURLConnection) connection); } } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (!isGet && HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { // don't proxy Referer headers if the referer is Selenium! if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) { continue; } if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // add any custom request headers that the user asked for Map<String, String> customRequestHeaders = AddCustomRequestHeaderCommand.getHeaders(); for (Map.Entry<String, String> e : customRequestHeaders.entrySet()) { connection.addRequestProperty(e.getKey(), e.getValue()); entry.addRequestHeader(e.getKey(), e.getValue()); } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = -1; if (http != null) { proxy_in = http.getErrorStream(); try { code = http.getResponseCode(); } catch (SSLHandshakeException e) { throw new RuntimeException("Couldn't establish SSL handshake. Try using trustAllSSLCertificates.\n" + e.getLocalizedMessage(), e); } response.setStatus(code); response.setReason(http.getResponseMessage()); String contentType = http.getContentType(); if (log.isDebugEnabled()) { log.debug("Content-Type is: " + contentType); } } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); response.removeField(HttpFields.__ETag); // possible cksum? Stop caching... response.removeField(HttpFields.__LastModified); // Stop caching... // Handled long bytesCopied = -1; request.setHandled(true); if (proxy_in != null) { boolean injectableResponse = http.getResponseCode() == HttpURLConnection.HTTP_OK || (http.getResponseCode() >= 400 && http.getResponseCode() < 600); if (proxyInjectionMode && injectableResponse) { // check if we should proxy this path based on the dontProxyRegex that can be user-specified if (shouldInject(request.getPath())) { bytesCopied = InjectionHelper.injectJavaScript(request, response, proxy_in, response.getOutputStream(), debugURL); } else { bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream()); } } else { bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream()); } } entry.finish(code, bytesCopied); entry.addResponseHeader(response); CaptureNetworkTrafficCommand.capture(entry); return bytesCopied; }
From source file:org.orbeon.oxf.util.Connection.java
/** * Open the connection. This sends request headers, request body, and reads status and response headers. * * @return connection result */// w w w.j av a2 s. c o m public ConnectionResult connect() { final boolean isDebugEnabled = indentedLogger.isDebugEnabled(); // Perform connection final String scheme = connectionURL.getProtocol(); if (isHTTPOrHTTPS(scheme) || (httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf")))) { // http MUST be supported // https SHOULD be supported // file SHOULD be supported try { // Create URL connection object final URLConnection urlConnection = connectionURL.openConnection(); final HTTPURLConnection httpURLConnection = (urlConnection instanceof HTTPURLConnection) ? (HTTPURLConnection) urlConnection : null; // Whether a message body must be sent final boolean hasRequestBody = httpMethod.equals("POST") || httpMethod.equals("PUT"); urlConnection.setDoInput(true); urlConnection.setDoOutput(hasRequestBody); // Configure HTTPURLConnection if (httpURLConnection != null) { // Set state if possible httpURLConnection.setCookieStore(this.cookieStore); // Set method httpURLConnection.setRequestMethod(httpMethod); // Set credentials if (credentials != null) { httpURLConnection.setUsername(credentials.username); if (credentials.password != null) httpURLConnection.setPassword(credentials.password); if (credentials.preemptiveAuthentication != null) httpURLConnection.setPreemptiveAuthentication(credentials.preemptiveAuthentication); if (credentials.domain != null) httpURLConnection.setDomain(credentials.domain); } } // Update request headers { // Handle SOAP // Set request Content-Type, SOAPAction or Accept header if needed final boolean didSOAP = handleSOAP(indentedLogger, httpMethod, headersMap, contentType, hasRequestBody); // Set request content type if (!didSOAP && hasRequestBody) { final String actualContentType = (contentType != null) ? contentType : "application/xml"; headersMap.put("Content-Type", new String[] { actualContentType }); indentedLogger.logDebug(LOG_TYPE, "setting header", "Content-Type", actualContentType); } } // Set headers on connection final List<String> headersToLog; if (headersMap != null && headersMap.size() > 0) { headersToLog = isDebugEnabled ? new ArrayList<String>() : null; for (Map.Entry<String, String[]> currentEntry : headersMap.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String[] currentHeaderValues = currentEntry.getValue(); if (currentHeaderValues != null) { // Add all header values as "request properties" for (String currentHeaderValue : currentHeaderValues) { urlConnection.addRequestProperty(currentHeaderName, currentHeaderValue); if (headersToLog != null) { headersToLog.add(currentHeaderName); headersToLog.add(currentHeaderValue); } } } } } else { headersToLog = null; } // Log request details except body if (isDebugEnabled) { // Basic connection information final URI connectionURI; try { String userInfo = connectionURL.getUserInfo(); if (userInfo != null) { final int colonIndex = userInfo.indexOf(':'); if (colonIndex != -1) userInfo = userInfo.substring(0, colonIndex + 1) + "xxxxxxxx";// hide password in logs } connectionURI = new URI(connectionURL.getProtocol(), userInfo, connectionURL.getHost(), connectionURL.getPort(), connectionURL.getPath(), connectionURL.getQuery(), connectionURL.getRef()); } catch (URISyntaxException e) { throw new OXFException(e); } indentedLogger.logDebug(LOG_TYPE, "opening URL connection", "method", httpMethod, "URL", connectionURI.toString(), "request Content-Type", contentType); // Log all headers if (headersToLog != null) { final String[] strings = new String[headersToLog.size()]; indentedLogger.logDebug(LOG_TYPE, "request headers", headersToLog.toArray(strings)); } } // Write request body if needed if (hasRequestBody) { // Case of empty body if (messageBody == null) messageBody = new byte[0]; // Log message body for debugging purposes if (logBody) logRequestBody(indentedLogger, contentType, messageBody); // Set request body on connection httpURLConnection.setRequestBody(messageBody); } // Connect urlConnection.connect(); if (httpURLConnection != null) { // Get state if possible // This is either the state we set above before calling connect(), or a new state if we didn't provide any this.cookieStore = httpURLConnection.getCookieStore(); } // Create result final ConnectionResult connectionResult = new ConnectionResult(connectionURL.toExternalForm()) { @Override public void close() { if (getResponseInputStream() != null) { try { getResponseInputStream().close(); } catch (IOException e) { throw new OXFException( "Exception while closing input stream for action: " + connectionURL); } } if (httpURLConnection != null) httpURLConnection.disconnect(); } }; // Get response information that needs to be forwarded { // Status code connectionResult.statusCode = (httpURLConnection != null) ? httpURLConnection.getResponseCode() : 200; // Headers connectionResult.responseHeaders = urlConnection.getHeaderFields(); connectionResult.setLastModified(NetUtils.getLastModifiedAsLong(urlConnection)); // Content-Type connectionResult.setResponseContentType(urlConnection.getContentType(), "application/xml"); } // Log response details except body if (isDebugEnabled) { connectionResult.logResponseDetailsIfNeeded(indentedLogger, Level.DEBUG, LOG_TYPE); } // Response stream connectionResult.setResponseInputStream(urlConnection.getInputStream()); // Log response body if (isDebugEnabled) { connectionResult.logResponseBody(indentedLogger, Level.DEBUG, LOG_TYPE, logBody); } return connectionResult; } catch (IOException e) { throw new ValidationException(e, new LocationData(connectionURL.toExternalForm(), -1, -1)); } } else if (!httpMethod.equals("GET") && (scheme.equals("file") || scheme.equals("oxf"))) { // TODO: implement writing to file: and oxf: // SHOULD be supported (should probably support oxf: as well) throw new OXFException("submission URL scheme not yet implemented: " + scheme); } else if (scheme.equals("mailto")) { // TODO: implement sending mail // MAY be supported throw new OXFException("submission URL scheme not yet implemented: " + scheme); } else { throw new OXFException("submission URL scheme not supported: " + scheme); } }