List of usage examples for org.apache.http.message BasicHttpEntityEnclosingRequest BasicHttpEntityEnclosingRequest
public BasicHttpEntityEnclosingRequest(String str, String str2)
From source file:com.elastica.browserfactory.RemoteDriverFactory.java
@Override public WebDriver createWebDriver() throws MalformedURLException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { DriverConfig webDriverConfig = this.getWebDriverConfig(); DesiredCapabilities capability = null; URL url;/*from w w w . j a v a 2 s. c o m*/ url = new URL(webDriverConfig.getHubUrl()); switch (webDriverConfig.getBrowser()) { case FireFox: capability = new FirefoxCapabilitiesFactory().createCapabilities(webDriverConfig); break; case InternetExplore: capability = new IECapabilitiesFactory().createCapabilities(webDriverConfig); break; case Chrome: capability = new ChromeCapabilitiesFactory().createCapabilities(webDriverConfig); break; case HtmlUnit: capability = new HtmlUnitCapabilitiesFactory().createCapabilities(webDriverConfig); break; case Safari: capability = new SafariCapabilitiesFactory().createCapabilities(webDriverConfig); break; case Android: capability = new AndroidCapabilitiesFactory().createCapabilities(webDriverConfig); break; case IPhone: capability = ((ICapabilitiesFactory) Class .forName("com.elastica.browserfactory.IPhoneCapabilitiesFactory").getConstructor() .newInstance()).createCapabilities(webDriverConfig); break; case IPad: capability = ((ICapabilitiesFactory) Class .forName("com.elastica.browserfactory.IPadCapabilitiesFactory").getConstructor().newInstance()) .createCapabilities(webDriverConfig); break; case Opera: capability = new OperaCapabilitiesFactory().createCapabilities(webDriverConfig); break; case PhantomJS: capability = new PhantomJSCapabilitiesFactory().createCapabilities(webDriverConfig); break; default: break; } switch (webDriverConfig.getBrowser()) { case IPhone: case IPad: driver = (WebDriver) Class.forName("com.elastica.browserfactory.RemoteIOSBaseDriver") .getConstructor(URL.class, DesiredCapabilities.class).newInstance(url, capability); break; case FireFox: try { driver = new ScreenShotRemoteWebDriver(url, capability); } catch (RuntimeException e) { if (e.getMessage().contains( "Unable to connect to host 127.0.0.1 on port 7062 after 45000 ms. Firefox console output")) { TestLogging.log("Firefox Driver creation got port customexception, retry after 5 seconds"); WaitHelper.waitForSeconds(5); driver = new ScreenShotRemoteWebDriver(url, capability); } else { throw e; } } break; default: driver = new ScreenShotRemoteWebDriver(url, capability); } setImplicitWaitTimeout(webDriverConfig.getImplicitWaitTimeout()); if (webDriverConfig.getPageLoadTimeout() >= 0) { setPageLoadTimeout(webDriverConfig.getPageLoadTimeout(), webDriverConfig.getBrowser()); } this.setWebDriver(driver); String hub = url.getHost(); int port = url.getPort(); // logging node ip address: try { HttpHost host = new HttpHost(hub, port); DefaultHttpClient client = new DefaultHttpClient(); String sessionUrl = "http://" + hub + ":" + port + "/grid/api/testsession?session="; URL session = new URL(sessionUrl + ((RemoteWebDriver) driver).getSessionId()); BasicHttpEntityEnclosingRequest req; req = new BasicHttpEntityEnclosingRequest("POST", session.toExternalForm()); org.apache.http.HttpResponse response = client.execute(host, req); String responseContent = EntityUtils.toString(response.getEntity()); try { JSONObject object = new JSONObject(responseContent); String proxyId = (String) object.get("proxyId"); String node = (proxyId.split("//")[1].split(":")[0]); String browserName = ((RemoteWebDriver) driver).getCapabilities().getBrowserName(); String version = ((RemoteWebDriver) driver).getCapabilities().getVersion(); System.out.println("WebDriver is running on node " + node + ", " + browserName + version + ", session " + ((RemoteWebDriver) driver).getSessionId()); TestLogging.log("WebDriver is running on node " + node + ", " + browserName + version + ", session " + ((RemoteWebDriver) driver).getSessionId()); } catch (org.json.JSONException e) { } } catch (Exception ex) { } return driver; }
From source file:com.comcast.cns.io.HTTPEndpointAsyncPublisher.java
@Override public void send() throws Exception { HttpAsyncRequester requester = new HttpAsyncRequester(httpProcessor, new DefaultConnectionReuseStrategy(), httpParams);/*from w ww . j a va 2 s . c o m*/ final URL url = new URL(endpoint); final HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getPath() + (url.getQuery() == null ? "" : "?" + url.getQuery())); composeHeader(request); String msg = null; if (message.getMessageStructure() == CNSMessageStructure.json) { msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http); } else { msg = message.getMessage(); } if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) { msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http); } logger.debug("event=send_async_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\""); request.setEntity(new NStringEntity(msg)); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), connectionPool, new BasicHttpContext(), new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { int statusCode = response.getStatusLine().getStatusCode(); // accept all 2xx status codes if (statusCode >= 200 && statusCode < 300) { callback.onSuccess(); } else { logger.warn(target + "://" + url.getPath() + "?" + url.getQuery() + " -> " + response.getStatusLine()); callback.onFailure(statusCode); } } public void failed(final Exception ex) { logger.warn(target + " " + url.getPath() + " " + url.getQuery(), ex); callback.onFailure(0); } public void cancelled() { logger.warn(target + " " + url.getPath() + " " + url.getQuery() + " -> " + "cancelled"); callback.onFailure(1); } }); }
From source file:microsoft.aspnet.signalr.client.http.android.AndroidHttpConnection.java
/** * Creates a request that can be accepted by the AndroidHttpClient * //from ww w .ja v a 2 s . c o m * @param request * The request information * @throws java.io.UnsupportedEncodingException */ private static BasicHttpEntityEnclosingRequest createRealRequest(Request request) throws UnsupportedEncodingException { BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(), request.getUrl()); if (request.getContent() != null) { realRequest.setEntity(new StringEntity(request.getContent())); } Map<String, String> headers = request.getHeaders(); for (String key : headers.keySet()) { realRequest.addHeader(key, headers.get(key)); } return realRequest; }
From source file:ste.web.http.beanshell.BugFreeBeanShellUtils.java
@Test public void bodyAsNotSpecifiedType() throws Exception { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("get", TEST_URI_PARAMETERS); HttpSessionContext context = new HttpSessionContext(); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, getConnection()); request.setEntity(new StringEntity("one=1&two=2")); Interpreter i = new Interpreter(); BeanShellUtils.setup(i, request, RESPONSE_OK, context); checkBodyAsNotSpecifiedType(i);/*from w ww . j a v a 2s. c o m*/ }
From source file:com.nominanuda.web.http.ServletHelper.java
public HttpRequest copyRequest(HttpServletRequest servletRequest, boolean stripContextPath) throws IOException { final InputStream is = getServletRequestBody(servletRequest); String method = servletRequest.getMethod(); String uri = getRequestLineURI(servletRequest, stripContextPath); String ct = servletRequest.getContentType(); @SuppressWarnings("unused") String charenc = getCharacterEncoding(servletRequest); String cenc = getContentEncoding(servletRequest); long contentLength = servletRequest.getContentLength(); HttpRequest req;/*from w w w . j a v a 2 s.c o m*/ if (is == null) { req = new BasicHttpRequest(method, uri); } else { req = new BasicHttpEntityEnclosingRequest(method, uri); HttpEntity entity = buildEntity(servletRequest, is, contentLength, ct, cenc); if (entity != null) { ((BasicHttpEntityEnclosingRequest) req).setEntity(entity); } } Enumeration<?> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration<?> vals = servletRequest.getHeaders(name); while (vals.hasMoreElements()) { String value = (String) vals.nextElement(); req.addHeader(name, value); } } return req; }
From source file:org.openqa.grid.internal.StatusServletTests.java
@Test public void testpost() throws IOException, JSONException { String id = "http://machine1:4444"; HttpClient client = httpClientFactory.getHttpClient(); JSONObject o = new JSONObject(); o.put("id", id); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", proxyApi.toExternalForm()); r.setEntity(new StringEntity(o.toString())); HttpResponse response = client.execute(host, r); assertEquals(200, response.getStatusLine().getStatusCode()); JSONObject res = extractObject(response); assertEquals(id, res.get("id")); }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java
public Bitmap getDMPicture(String picUrl, Twitter twitter) { try {/*from ww w . java 2s .com*/ AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = picUrl; String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "") .replace("/", ""); String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", ""); String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host); Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); StatusLine statusLine = response2.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 || statusCode == 302) { HttpEntity entity = response2.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { Log.v("talon_dm_image", statusCode + ""); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:snoopware.api.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;// w w w.ja v a2 s.com //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURL().toString() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but // it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java
@SuppressWarnings("deprecation") @Override// www . j a va 2s .c om protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest; //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:uk.co.bubobubo.web.HttpClientProxy.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;// w ww .j a va 2 s .c o m //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyRequest.removeHeaders("authorization"); if (targetUri.getUserInfo() != null && !targetUri.getUserInfo().equalsIgnoreCase("") && !targetUri.getUserInfo().equalsIgnoreCase(":")) { Credentials credentials = new UsernamePasswordCredentials(targetUri.getUserInfo().split(":")[0], targetUri.getUserInfo().split(":")[1]); proxyClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }