List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
From source file:org.switchyard.component.http.OutboundHandler.java
/** * The handler method that invokes the actual HTTP service when the * component is used as a HTTP consumer. * @param exchange the Exchange//from ww w.j av a 2 s . c o m * @throws HandlerException handler exception */ @Override public void handleMessage(final Exchange exchange) throws HandlerException { // identify ourselves exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) .addLabels(BehaviorLabel.TRANSIENT.label()); if (getState() != State.STARTED) { final String m = HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName); LOGGER.error(m); throw new HandlerException(m); } HttpClient httpclient = new DefaultHttpClient(); if (_timeout != null) { HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, _timeout); HttpConnectionParams.setSoTimeout(httpParams, _timeout); } try { if (_credentials != null) { ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials); List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); authpref.add(AuthPolicy.BASIC); httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); } if (_proxyHost != null) { httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost); } HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData()); HttpRequestBase request = null; if (_httpMethod.equals(HTTP_GET)) { request = new HttpGet(_baseAddress); } else if (_httpMethod.equals(HTTP_POST)) { request = new HttpPost(_baseAddress); ((HttpPost) request).setEntity(new BufferedHttpEntity( new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available()))); } else if (_httpMethod.equals(HTTP_DELETE)) { request = new HttpDelete(_baseAddress); } else if (_httpMethod.equals(HTTP_HEAD)) { request = new HttpHead(_baseAddress); } else if (_httpMethod.equals(HTTP_PUT)) { request = new HttpPut(_baseAddress); ((HttpPut) request).setEntity(new BufferedHttpEntity( new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available()))); } else if (_httpMethod.equals(HTTP_OPTIONS)) { request = new HttpOptions(_baseAddress); } Iterator<Map.Entry<String, List<String>>> entries = httpRequest.getHeaders().entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, List<String>> entry = entries.next(); String name = entry.getKey(); if (REQUEST_HEADER_BLACKLIST.contains(name)) { HttpLogger.ROOT_LOGGER.removingProhibitedRequestHeader(name); continue; } List<String> values = entry.getValue(); for (String value : values) { request.addHeader(name, value); } } if (_contentType != null) { request.addHeader("Content-Type", _contentType); } HttpResponse response = null; if ((_credentials != null) && (_credentials instanceof NTCredentials)) { // Send a request for the Negotiation response = httpclient.execute(new HttpGet(_baseAddress)); HttpClientUtils.closeQuietly(response); } if (_authCache != null) { BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, _authCache); response = httpclient.execute(request, context); } else { response = httpclient.execute(request); } int status = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); HttpResponseBindingData httpResponse = new HttpResponseBindingData(); Header[] headers = response.getAllHeaders(); for (Header header : headers) { httpResponse.addHeader(header.getName(), header.getValue()); } if (entity != null) { if (entity.getContentType() != null) { httpResponse.setContentType(new ContentType(entity.getContentType().getValue())); } else { httpResponse.setContentType(new ContentType()); } httpResponse.setBodyFromStream(entity.getContent()); } httpResponse.setStatus(status); Message out = _messageComposer.compose(httpResponse, exchange); if (httpResponse.getStatus() < 400) { exchange.send(out); } else { exchange.sendFault(out); } } catch (Exception e) { final String m = HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage(); LOGGER.error(m, e); throw new HandlerException(m, e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.smartsheet.api.internal.http.DefaultHttpClient.java
/** * Make an HTTP request and return the response. * * @param smartsheetRequest the smartsheet request * @return the HTTP response//from ww w. j ava2 s.co m * @throws HttpClientException the HTTP client exception */ public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException { Util.throwIfNull(smartsheetRequest); if (smartsheetRequest.getUri() == null) { throw new IllegalArgumentException("A Request URI is required."); } int attempt = 0; long start = System.currentTimeMillis(); HttpRequestBase apacheHttpRequest; HttpResponse smartsheetResponse; InputStream bodyStream = null; if (smartsheetRequest.getEntity() != null && smartsheetRequest.getEntity().getContent() != null) { bodyStream = smartsheetRequest.getEntity().getContent(); } // the retry logic will consume the body stream so we make sure it supports mark/reset and mark it boolean canRetryRequest = bodyStream == null || bodyStream.markSupported(); if (!canRetryRequest) { try { // attempt to wrap the body stream in a input-stream that does support mark/reset bodyStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(bodyStream)); // close the old stream (just to be tidy) and then replace it with a reset-able stream smartsheetRequest.getEntity().getContent().close(); smartsheetRequest.getEntity().setContent(bodyStream); canRetryRequest = true; } catch (IOException ignore) { } } // the retry loop while (true) { apacheHttpRequest = createApacheRequest(smartsheetRequest); // Set HTTP headers if (smartsheetRequest.getHeaders() != null) { for (Map.Entry<String, String> header : smartsheetRequest.getHeaders().entrySet()) { apacheHttpRequest.addHeader(header.getKey(), header.getValue()); } } HttpEntitySnapshot requestEntityCopy = null; HttpEntitySnapshot responseEntityCopy = null; // Set HTTP entity final HttpEntity entity = smartsheetRequest.getEntity(); if (apacheHttpRequest instanceof HttpEntityEnclosingRequestBase && entity != null && entity.getContent() != null) { try { // we need access to the original request stream so we can log it (in the event of errors and/or tracing) requestEntityCopy = new HttpEntitySnapshot(entity); } catch (IOException iox) { logger.error("failed to make copy of original request entity - {}", iox); } InputStreamEntity streamEntity = new InputStreamEntity(entity.getContent(), entity.getContentLength()); streamEntity.setChunked(false); // why? not supported by library? ((HttpEntityEnclosingRequestBase) apacheHttpRequest).setEntity(streamEntity); } // mark the body so we can reset on retry if (canRetryRequest && bodyStream != null) { bodyStream.mark((int) smartsheetRequest.getEntity().getContentLength()); } // Make the HTTP request smartsheetResponse = new HttpResponse(); HttpContext context = new BasicHttpContext(); try { long startTime = System.currentTimeMillis(); apacheHttpResponse = this.httpClient.execute(apacheHttpRequest, context); long endTime = System.currentTimeMillis(); // Set request headers to values ACTUALLY SENT (not just created by us), this would include: // 'Connection', 'Accept-Encoding', etc. However, if a proxy is used, this may be the proxy's CONNECT // request, hence the test for HTTP method first Object httpRequest = context.getAttribute("http.request"); if (httpRequest != null && HttpRequestWrapper.class.isAssignableFrom(httpRequest.getClass())) { HttpRequestWrapper actualRequest = (HttpRequestWrapper) httpRequest; switch (HttpMethod.valueOf(actualRequest.getMethod())) { case GET: case POST: case PUT: case DELETE: apacheHttpRequest.setHeaders(((HttpRequestWrapper) httpRequest).getAllHeaders()); break; } } // Set returned headers smartsheetResponse.setHeaders(new HashMap<String, String>()); for (Header header : apacheHttpResponse.getAllHeaders()) { smartsheetResponse.getHeaders().put(header.getName(), header.getValue()); } smartsheetResponse.setStatus(apacheHttpResponse.getStatusLine().getStatusCode(), apacheHttpResponse.getStatusLine().toString()); // Set returned entities if (apacheHttpResponse.getEntity() != null) { HttpEntity httpEntity = new HttpEntity(); httpEntity.setContentType(apacheHttpResponse.getEntity().getContentType().getValue()); httpEntity.setContentLength(apacheHttpResponse.getEntity().getContentLength()); httpEntity.setContent(apacheHttpResponse.getEntity().getContent()); smartsheetResponse.setEntity(httpEntity); responseEntityCopy = new HttpEntitySnapshot(httpEntity); } long responseTime = endTime - startTime; logRequest(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, responseTime); if (traces.size() > 0) { // trace-logging of request and response (if so configured) RequestAndResponseData requestAndResponseData = RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, traces); TRACE_WRITER.println(requestAndResponseData.toString(tracePrettyPrint)); } if (smartsheetResponse.getStatusCode() == 200) { // call successful, exit the retry loop break; } // the retry logic might consume the content stream so we make sure it supports mark/reset and mark it InputStream contentStream = smartsheetResponse.getEntity().getContent(); if (!contentStream.markSupported()) { // wrap the response stream in a input-stream that does support mark/reset contentStream = new ByteArrayInputStream(StreamUtil.readBytesFromStream(contentStream)); // close the old stream (just to be tidy) and then replace it with a reset-able stream smartsheetResponse.getEntity().getContent().close(); smartsheetResponse.getEntity().setContent(contentStream); } try { contentStream.mark((int) smartsheetResponse.getEntity().getContentLength()); long timeSpent = System.currentTimeMillis() - start; if (!shouldRetry(++attempt, timeSpent, smartsheetResponse)) { // should not retry, or retry time exceeded, exit the retry loop break; } } finally { if (bodyStream != null) { bodyStream.reset(); } contentStream.reset(); } // moving this to finally causes issues because socket is closed (which means response stream is closed) this.releaseConnection(); } catch (ClientProtocolException e) { try { logger.warn("ClientProtocolException " + e.getMessage()); logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY)); // if this is a PUT and was retried by the http client, the body content stream is at the // end and is a NonRepeatableRequest. If we marked the body content stream prior to execute, // reset and retry if (canRetryRequest && e.getCause() instanceof NonRepeatableRequestException) { if (smartsheetRequest.getEntity() != null) { smartsheetRequest.getEntity().getContent().reset(); } continue; } } catch (IOException ignore) { } throw new HttpClientException("Error occurred.", e); } catch (NoHttpResponseException e) { try { logger.warn("NoHttpResponseException " + e.getMessage()); logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY)); // check to see if the response was empty and this was a POST. All other HTTP methods // will be automatically retried by the http client. // (POST is non-idempotent and is not retried automatically, but is safe for us to retry) if (canRetryRequest && smartsheetRequest.getMethod() == HttpMethod.POST) { if (smartsheetRequest.getEntity() != null) { smartsheetRequest.getEntity().getContent().reset(); } continue; } } catch (IOException ignore) { } throw new HttpClientException("Error occurred.", e); } catch (IOException e) { try { logger.warn("{}", RequestAndResponseData.of(apacheHttpRequest, requestEntityCopy, smartsheetResponse, responseEntityCopy, REQUEST_RESPONSE_SUMMARY)); } catch (IOException ignore) { } throw new HttpClientException("Error occurred.", e); } } return smartsheetResponse; }
From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); if (req.getParameter("update") != null) { uri.append(targetUri).append("/").append(req.getParameter("update")); } else {/*w ww. java 2 s . c o m*/ uri.append(targetUri); } LOG.info("Access URI : " + uri.toString()); // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<?> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); String headerValue = req.getHeader(headerName); //LOG.info("header: " + headerName + " value: " + headerValue); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-type")) { request.addHeader(headerName, headerValue + ";charset=\"utf-8\""); } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) { request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; if (!header.getName().equals("Transfer-Encoding")) resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); byte buffer[] = new byte[50]; while (input.read(buffer) != -1) { output.write(buffer); } // int b = input.read(); // while (b != -1) { // output.write(b); // b = input.read(); // } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:org.xmlsh.internal.commands.http.java
@Override public int run(List<XValue> args) throws Exception { Options opts = new Options( "retry:,get:,put:,post:,head:,options:,delete:,connectTimeout:,contentType:,readTimeout:,+useCaches,+followRedirects,user:,password:,H=add-header:+,disableTrust:,keystore:,keypass:,sslproto:,output-headers=ohead:"); opts.parse(args);//from w ww. j av a2s.c o m setSerializeOpts(getSerializeOpts(opts)); HttpRequestBase method; String surl = null; if (opts.hasOpt("get")) { surl = opts.getOptString("get", null); method = new HttpGet(surl); } else if (opts.hasOpt("put")) { surl = opts.getOptString("put", null); method = new HttpPut(surl); ((HttpPut) method).setEntity(getInputEntity(opts)); } else if (opts.hasOpt("post")) { surl = opts.getOptString("post", null); method = new HttpPost(surl); ((HttpPost) method).setEntity(getInputEntity(opts)); } else if (opts.hasOpt("head")) { surl = opts.getOptString("head", null); method = new HttpHead(surl); } else if (opts.hasOpt("options")) { surl = opts.getOptString("options", null); method = new HttpOptions(surl); } else if (opts.hasOpt("delete")) { surl = opts.getOptString("delete", null); method = new HttpDelete(surl); } else if (opts.hasOpt("trace")) { surl = opts.getOptString("trace", null); method = new HttpTrace(surl); } else { surl = opts.getRemainingArgs().get(0).toString(); method = new HttpGet(surl); } if (surl == null) { usage(); return 1; } int ret = 0; HttpHost host = new HttpHost(surl); DefaultHttpClient client = new DefaultHttpClient(); setOptions(client, host, opts); List<XValue> headers = opts.getOptValues("H"); if (headers != null) { for (XValue v : headers) { StringPair pair = new StringPair(v.toString(), '='); method.addHeader(pair.getLeft(), pair.getRight()); } } int retry = opts.getOptInt("retry", 0); long delay = 1000; HttpResponse resp = null; do { try { resp = client.execute(method); break; } catch (IOException e) { mShell.printErr("Exception running http" + ((retry > 0) ? " retrying ... " : ""), e); if (retry > 0) { Thread.sleep(delay); delay *= 2; } else throw e; } } while (retry-- > 0); HttpEntity respEntity = resp.getEntity(); if (respEntity != null) { InputStream ins = respEntity.getContent(); if (ins != null) { try { Util.copyStream(ins, getStdout().asOutputStream(getSerializeOpts())); } finally { ins.close(); } } } ret = resp.getStatusLine().getStatusCode(); if (opts.hasOpt("output-headers")) writeHeaders(opts.getOptStringRequired("output-headers"), resp.getStatusLine(), resp.getAllHeaders()); return ret; }
From source file:com.web.server.ProxyServlet.java
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Create new client to perform the proxied request HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); uri.append(targetServer);//from ww w . ja va 2s .c o m uri.append(req.getRequestURI()); // Add any supplied query strings String queryString = req.getQueryString(); if (queryString != null) { uri.append("?" + queryString); } // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); String headerValue = req.getHeader(headerName); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) { // System.out.println(headerName.toLowerCase() + ": " + headerValue); request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); int b = input.read(); while (b != -1) { output.write(b); b = input.read(); } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:org.gnode.wda.server.ProxyServlet.java
License:asdf
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Create new client to perform the proxied request HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); uri.append(targetServer);//from www. j a v a 2s. c o m // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method. // Turns "/proxy/asdf" into "/asdf" uri.append(req.getRequestURI().substring(6)); // Add any supplied query strings String queryString = req.getQueryString(); if (queryString != null) { uri.append("?" + queryString); } // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); String headerValue = req.getHeader(headerName); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) { // System.out.println(headerName.toLowerCase() + ": " + headerValue); request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); if (entity == null) return; InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); int b = input.read(); while (b != -1) { output.write(b); b = input.read(); } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:de.betterform.connector.http.AbstractHTTPConnector.java
protected void execute(HttpRequestBase httpRequestBase) throws Exception { // (new HttpClient()).executeMethod(httpMethod); //HttpClient client = new HttpClient(); HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams); if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("SSL_CUSTOM_SCHEME"); LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: " + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT)); String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT); if (contextPath != null) { initSSLScheme(contextPath);//from w ww . j av a 2 s .c om } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("context params>>>"); Map map = getContext(); Iterator keys = map.keySet().iterator(); while (keys.hasNext()) { String key = keys.next().toString(); Object value = map.get(key); if (value != null) LOGGER.debug(key + "=" + value.toString()); } LOGGER.debug("<<<end params"); } String username = null; String password = null; String realm = null; //add custom header to signal XFormsFilter to not process this internal request //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true"); httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true"); /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders if (getContext().containsKey(HTTP_REQUEST_HEADERS)) { RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS); // Iterator it = Map headersToAdd = new HashMap(); for (RequestHeader header : httpRequestHeaders.getAllHeaders()) { String headername = header.getName(); String headervalue = header.getValue(); if (headername.equals("username")) { username = headervalue; } else if (headername.equals("password")) { password = headervalue; } else if (headername.equals("realm")) { realm = headervalue; } else { if (headersToAdd.containsKey(headername)) { String formerValue = (String) headersToAdd.get(headername); headersToAdd.put(headername, formerValue + "," + headervalue); } else { if (headername.equals("accept-encoding")) { // do nothing LOGGER.debug("do not add accept-encoding:" + headervalue + " for request"); } else { headersToAdd.put(headername, headervalue); if (LOGGER.isDebugEnabled()) { LOGGER.debug("setting header: " + headername + " value: " + headervalue); } } } } } Iterator keyIterator = headersToAdd.keySet().iterator(); while (keyIterator.hasNext()) { String key = (String) keyIterator.next(); //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key))); httpRequestBase.setHeader(key, (String) headersToAdd.get(key)); //httpRequestBase.addHeader(key, (String) headersToAdd.get(key)); } } if (httpRequestBase.containsHeader("Content-Length")) { //remove content-length if present httpclient will recalucalte the value. httpRequestBase.removeHeaders("Content-Length"); } if (username != null && password != null) { URI targetURI = null; //targetURI = httpMethod.getURI(); targetURI = httpRequestBase.getURI(); //client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); if (realm == null) { realm = AuthScope.ANY_REALM; } //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); client.getCredentialsProvider() .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(targetURI.getHost()), basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); //Needed? httpMethod.setDoAuthentication(true); } //alternative method for non-tomcat servers if (getContext().containsKey(REQUEST_COOKIE)) { //HttpState state = client.getState(); HttpParams state = client.getParams(); //state.setCookiePolicy(CookiePolicy.COMPATIBILITY); state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) { Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE); if (cookiesIn[0] != null) { for (int i = 0; i < cookiesIn.length; i++) { Cookie cookie = cookiesIn[i]; //state.addCookie(cookie); client.getCookieStore().addCookie(cookie); } /* Cookie[] cookies = state.getCookies(); Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies); httpMethod.setRequestHeader(cookieOut); client.setState(state); */ List<Cookie> cookies = client.getCookieStore().getCookies(); List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies); Header[] headers = cookieHeaders.toArray(new Header[0]); for (int i = 0; i < headers.length; i++) { httpRequestBase.addHeader(headers[i]); } client.setParams(state); } } else { throw new MalformedCookieException( "Cookies must be passed as org.apache.commons.httpclient.Cookie objects."); } } if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("Using customSSL-Protocol-Handler"); Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) .iterator(); while (schemes.hasNext()) { client.getConnectionManager().getSchemeRegistry().register(schemes.next()); } } if (httpRequestBase.getURI().isAbsolute()) { httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost()); } HttpResponse httpResponse = client.execute(httpRequestBase); statusCode = httpResponse.getStatusLine().getStatusCode(); reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); try { if (statusCode >= 300) { // Allow 302 only if (statusCode != 302) { throw new XFormsInternalSubmitException(statusCode, reasonPhrase, EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } } this.handleHttpMethod(httpResponse); } catch (Exception e) { LOGGER.trace("AbstractHTTPConnector Exception: ", e); try { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } catch (IOException e1) { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR); } } }
From source file:net.ychron.unirestinst.http.HttpClientHelper.java
private HttpRequestBase prepareRequest(HttpRequest request, boolean async) { Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS); if (defaultHeaders != null) { @SuppressWarnings("unchecked") Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet(); for (Entry<String, String> entry : entrySet) { request.header(entry.getKey(), entry.getValue()); }/* w w w . jav a 2 s . c o m*/ } if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) { request.header(USER_AGENT_HEADER, USER_AGENT); } if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) { request.header(ACCEPT_ENCODING_HEADER, "gzip"); } HttpRequestBase reqObj = null; String urlToRequest = null; try { URL url = new URL(request.getUrl()); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef()); urlToRequest = uri.toURL().toString(); if (url.getQuery() != null && !url.getQuery().trim().equals("")) { if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest += "?"; } urlToRequest += url.getQuery(); } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) { urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1); } } catch (Exception e) { throw new RuntimeException(e); } switch (request.getHttpMethod()) { case GET: reqObj = new HttpGet(urlToRequest); break; case POST: reqObj = new HttpPost(urlToRequest); break; case PUT: reqObj = new HttpPut(urlToRequest); break; case DELETE: reqObj = new HttpDeleteWithBody(urlToRequest); break; case PATCH: reqObj = new HttpPatchWithBody(urlToRequest); break; case OPTIONS: reqObj = new HttpOptions(urlToRequest); break; case HEAD: reqObj = new HttpHead(urlToRequest); break; } Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet(); for (Entry<String, List<String>> entry : entrySet) { List<String> values = entry.getValue(); if (values != null) { for (String value : values) { reqObj.addHeader(entry.getKey(), value); } } } // Set body if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) { if (request.getBody() != null) { HttpEntity entity = request.getBody().getEntity(); if (async) { if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) { reqObj.setHeader(entity.getContentType()); } try { ByteArrayOutputStream output = new ByteArrayOutputStream(); entity.writeTo(output); NByteArrayEntity en = new NByteArrayEntity(output.toByteArray()); ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en); } catch (IOException e) { throw new RuntimeException(e); } } else { ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity); } } } return reqObj; }
From source file:net.sf.jasperreports.data.http.HttpDataService.java
protected HttpRequestBase createRequest(Map<String, Object> parameters) { URI requestURI = getRequestURI(parameters); RequestMethod method = getMethod(parameters); String body = getBody(parameters); List<NameValuePair> postParameters = collectPostParameters(parameters); if (method == null) { method = (body == null && postParameters.isEmpty()) ? RequestMethod.GET : RequestMethod.POST; }//w w w . jav a 2 s. c o m HttpRequestBase request; switch (method) { case GET: if (body != null) { log.warn("Ignoring request body for GET request to " + dataLocation.getUrl()); } if (!postParameters.isEmpty()) { log.warn("Ignoring POST parameters for GET request to " + dataLocation.getUrl()); } request = createGetRequest(requestURI); break; case POST: if (body == null) { request = createPostRequest(requestURI, postParameters); } else { if (!postParameters.isEmpty()) { log.warn("Ignoring POST parameters for POST request having request body to " + dataLocation.getUrl()); } request = createPostRequest(requestURI, body); } break; case PUT: if (body == null) { request = createPutRequest(requestURI, postParameters); } else { if (!postParameters.isEmpty()) { log.warn("Ignoring POST parameters for PUT request having request body to " + dataLocation.getUrl()); } request = createPutRequest(requestURI, body); } break; default: throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_UNKNOWN_REQUEST_METHOD, new Object[] { method }); } List<NameValuePair> headers = collectHeaders(parameters); if (headers != null) { for (NameValuePair header : headers) { request.addHeader(header.getName(), header.getValue()); } } return request; }
From source file:com.lehman.ic9.net.httpClient.java
/** * Performs the actual HTTP request. This method is called from the GET and POST * methods. //from ww w. java 2s . com * @param getString is a boolean flag with true for string and false for binary. * @param post is a boolean flag with true for post and false for get. * @return A Javascript object with the results of the request. * @throws ic9exception Exception * @throws NoSuchMethodException Exception * @throws ScriptException Exception */ private Map<String, Object> performRequest(boolean getString, httpReqType reqType) throws ic9exception, NoSuchMethodException, ScriptException { Map<String, Object> ret = this.eng.newObj(null); HttpRequestBase httpReq = null; if (reqType == httpReqType.GET) httpReq = new HttpGet(this.u.toString()); else if (reqType == httpReqType.POST) httpReq = new HttpPost(this.u.toString()); else if (reqType == httpReqType.PUT) httpReq = new HttpPut(this.u.toString()); else if (reqType == httpReqType.DELETE) httpReq = new HttpDelete(this.u.toString()); // Set cookies from JS object. this.cs.clear(); Object[] jscookies = (Object[]) this.eng.getJavaArray(this.jsobj.get("cookies")); for (Object tobj : jscookies) { @SuppressWarnings("unchecked") Map<String, Object> cobj = (Map<String, Object>) tobj; this.cs.addCookie(this.setApacheCookie(cobj)); } HttpClientContext ctx = HttpClientContext.create(); ctx.setCookieStore(this.cs); ctx.setCredentialsProvider(this.cp); ctx.setRequestConfig(this.rcb.build()); // Set headers. @SuppressWarnings("unchecked") Map<String, Object> headers = (Map<String, Object>) this.jsobj.get("headers"); for (String key : headers.keySet()) { String val = (String) headers.get(key); httpReq.addHeader(key, val); } CloseableHttpResponse resp = null; try { if (this.cli == null) { this.buildClient(httpReq); } if (reqType == httpReqType.POST && this.respEnt != null) ((HttpPost) httpReq).setEntity(this.respEnt); else if (reqType == httpReqType.PUT && this.respEnt != null) ((HttpPut) httpReq).setEntity(this.respEnt); resp = this.cli.execute(httpReq, ctx); HttpEntity ent = resp.getEntity(); this.getResponseInfo(ret, resp); if (ent != null) { if (getString) ret.put("content", this.getContentString(ent.getContent())); else { Map<String, Object> obj = this.eng.newObj("Buffer"); obj.put("data", this.getContentBinary(ent.getContent())); ret.put("content", obj); } EntityUtils.consume(ent); } } catch (ClientProtocolException e) { throw new ic9exception("httpClient.performRequest(): Client protocol exception. " + e.getMessage()); } catch (IOException e) { throw new ic9exception("httpClient.performRequest(): IO exception. " + e.getMessage()); } catch (KeyManagementException e) { throw new ic9exception("httpClient.performRequest(): Key management exception. " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new ic9exception("httpClient.performRequest(): No such algorithm exception. " + e.getMessage()); } catch (KeyStoreException e) { throw new ic9exception("httpClient.performRequest(): Key store exception. " + e.getMessage()); } catch (AuthenticationException e) { throw new ic9exception("httpClient.performRequest(): Authentication exception. " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); throw new ic9exception("httpClient.performRequest(): Unhandled exception. " + e.getMessage()); } finally { // Reset credentials if (this.creds != null) { this.creds = null; this.atype = authType.NONE; } if (resp != null) { try { resp.close(); } catch (IOException e) { } } if (reqType == httpReqType.POST || reqType == httpReqType.PUT) this.respEnt = null; } // Release the connection. httpReq.releaseConnection(); return ret; }