List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext
public BasicHttpContext()
From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java
@Override public Response execute(Command command) throws IOException { HttpContext context = new BasicHttpContext(); if (command.getSessionId() == null) { if (QUIT.equals(command.getName())) { return new Response(); }/*from w w w .jav a 2 s . co m*/ if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) { throw new SessionNotFoundException("Session ID is null. Using WebDriver after calling quit()?"); } } HttpRequest request = commandCodec.encode(command); String requestUrl = remoteServer.toExternalForm().replaceAll("/$", "") + request.getUri(); HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl); for (String name : request.getHeaderNames()) { // Skip content length as it is implicitly set when the message entity is set below. if (!"Content-Length".equalsIgnoreCase(name)) { for (String value : request.getHeaders(name)) { httpMethod.addHeader(name, value); } } } if (httpMethod instanceof HttpPost) { ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent())); } if (requestTimeout > 0 && (httpMethod instanceof HttpRequestBase)) { RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(15000) .setConnectTimeout(15000).setSocketTimeout(requestTimeout).build(); ((HttpRequestBase) httpMethod).setConfig(requestConfig); } else if (httpMethod instanceof HttpRequestBase) { // ensure Selenium Standard is set RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000) .setConnectTimeout(60000).setSocketTimeout(THREE_HOURS).build(); ((HttpRequestBase) httpMethod).setConfig(requestConfig); } try { log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true)); HttpResponse response = fallBackExecute(context, httpMethod); log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false)); lastResponse = response; response = followRedirects(client, context, response, /* redirect count */0); lastResponse = response; return createResponse(response, context); } catch (UnsupportedCommandException e) { if (e.getMessage() == null || "".equals(e.getMessage())) { throw new UnsupportedOperationException( "No information from server. Command name was: " + command.getName(), e.getCause()); } throw e; } catch (SocketTimeoutException e) { LoggerFactory.getLogger(AludraSeleniumHttpCommandExecutor.class) .warn("Timeout in HTTP Command Executor. Timeout was " + ((HttpRequestBase) httpMethod).getConfig().getSocketTimeout()); throw e; } }
From source file:com.entertailion.android.dial.MainActivity.java
@Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if (requestCode == CODE_SWITCH_SERVER) { if (resultCode == RESULT_OK && data != null) { final DialServer dialServer = data.getParcelableExtra(ServerFinder.EXTRA_DIAL_SERVER); if (dialServer != null) { Toast.makeText(MainActivity.this, getString(R.string.finder_connected, dialServer.toString()), Toast.LENGTH_LONG).show(); new Thread(new Runnable() { public void run() { try { String device = "http://" + dialServer.getIpAddress().getHostAddress() + ":" + dialServer.getPort(); Log.d(LOG_TAG, "device=" + device); Log.d(LOG_TAG, "apps url=" + dialServer.getAppsUrl()); // application instance url String location = null; String app = YOU_TUBE; DefaultHttpClient defaultHttpClient = HttpRequestHelper.createHttpClient(); CustomRedirectHandler handler = new CustomRedirectHandler(); defaultHttpClient.setRedirectHandler(handler); BasicHttpContext localContext = new BasicHttpContext(); // check if any app is running HttpGet httpGet = new HttpGet(dialServer.getAppsUrl()); httpGet.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE); httpGet.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE); httpGet.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE); httpGet.setHeader(HEADER_DNT, HEADER_DNT_VALUE); httpGet.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE); httpGet.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); if (httpResponse != null) { int responseCode = httpResponse.getStatusLine().getStatusCode(); Log.d(LOG_TAG, "get response code=" + httpResponse.getStatusLine().getStatusCode()); if (responseCode == 204) { // nothing is running } else if (responseCode == 200) { // app is running // Need to get real URL after a redirect // http://stackoverflow.com/a/10286025/594751 String lastUrl = dialServer.getAppsUrl(); if (handler.lastRedirectedUri != null) { lastUrl = handler.lastRedirectedUri.toString(); Log.d(LOG_TAG, "lastUrl=" + lastUrl); }//from w w w. ja v a 2 s . c o m String response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "get response=" + response); parseXml(MainActivity.this, new StringReader(response)); Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue()); } // stop the app instance HttpDelete httpDelete = new HttpDelete(lastUrl); httpResponse = defaultHttpClient.execute(httpDelete); if (httpResponse != null) { Log.d(LOG_TAG, "delete response code=" + httpResponse.getStatusLine().getStatusCode()); response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "delete response=" + response); } else { Log.d(LOG_TAG, "no delete response"); } } } else { Log.i(LOG_TAG, "no get response"); return; } // Check if app is installed on device int responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app); if (responseCode != 200) { return; } parseXml(MainActivity.this, new StringReader(response)); Log.d(LOG_TAG, "state=" + state); // start the app with POST HttpPost httpPost = new HttpPost(dialServer.getAppsUrl() + app); httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE); httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE); httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE); httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE); httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE); httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE); httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE); httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_TEXT_VALUE); // Set variable values as the body of the POST; // v is the YouTube video id. httpPost.setEntity(new StringEntity( "pairingCode=eac4ae42-8b54-4441-9be3-d8a9abb5c481&v=cKG5HDyTW8o&t=0")); // http://www.youtube.com/watch?v=cKG5HDyTW8o httpResponse = defaultHttpClient.execute(httpPost, localContext); if (httpResponse != null) { Log.d(LOG_TAG, "post response code=" + httpResponse.getStatusLine().getStatusCode()); response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "post response=" + response); Header[] headers = httpResponse.getHeaders("LOCATION"); if (headers.length > 0) { location = headers[0].getValue(); Log.d(LOG_TAG, "post response location=" + location); } headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue()); } } else { Log.i(LOG_TAG, "no post response"); return; } // Keep trying to get the app status until the // connection service URL is available state = STATE_STOPPED; do { responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app); if (responseCode != 200) { break; } parseXml(MainActivity.this, new StringReader(response)); Log.d(LOG_TAG, "state=" + state); Log.d(LOG_TAG, "connectionServiceUrl=" + connectionServiceUrl); Log.d(LOG_TAG, "protocol=" + protocol); try { Thread.sleep(1000); } catch (Exception e) { } } while (state.equals(STATE_RUNNING) && connectionServiceUrl == null); if (connectionServiceUrl == null) { Log.i(LOG_TAG, "connectionServiceUrl is null"); return; // oops, something went wrong } // get the websocket URL String webSocketAddress = null; httpPost = new HttpPost(connectionServiceUrl); // "http://192.168.0.17:8008/connection/YouTube" httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE); httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE); httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE); httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE); httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE); httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE); httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE); httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_JSON_VALUE); httpPost.setEntity(new StringEntity( "{\"channel\":0,\"senderId\":{\"appName\":\"ChromeCast\", \"senderId\":\"7v3zqrpliq3i\"}}")); httpResponse = defaultHttpClient.execute(httpPost, localContext); if (httpResponse != null) { responseCode = httpResponse.getStatusLine().getStatusCode(); Log.d(LOG_TAG, "post response code=" + responseCode); if (responseCode == 200) { // should return JSON payload response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "post response=" + response); Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue()); } JSONObject jObject; try { jObject = new JSONObject(response); // {"URL":"ws://192.168.0.17:8008/session?33","pingInterval":0} webSocketAddress = jObject.getString("URL"); Log.d(LOG_TAG, "webSocketAddress: " + webSocketAddress); int pingInterval = jObject.optInt("pingInterval"); // TODO } catch (JSONException e) { Log.e(LOG_TAG, "JSON", e); } } } else { Log.i(LOG_TAG, "no post response"); return; } // Make a web socket connection for doing RAMP // to control media playback if (webSocketAddress != null) { // https://github.com/koush/android-websockets List<BasicNameValuePair> extraHeaders = Arrays.asList( new BasicNameValuePair(HEADER_ORIGN, HEADER_ORIGIN_VALUE), new BasicNameValuePair("Pragma", "no-cache"), new BasicNameValuePair("Cache-Control", "no-cache"), new BasicNameValuePair(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE)); client = new WebSocketClient(URI.create(webSocketAddress), new WebSocketClient.Listener() { // ws://192.168.0.17:8008/session?26 @Override public void onConnect() { Log.d(LOG_TAG, "Websocket Connected!"); // TODO RAMP commands } @Override public void onMessage(String message) { Log.d(LOG_TAG, String.format("Websocket Got string message! %s", message)); } @Override public void onMessage(byte[] data) { Log.d(LOG_TAG, String.format("Websocket Got binary message! %s", data)); } @Override public void onDisconnect(int code, String reason) { Log.d(LOG_TAG, String.format( "Websocket Disconnected! Code: %d Reason: %s", code, reason)); } @Override public void onError(Exception error) { Log.e(LOG_TAG, "Websocket Error!", error); } }, extraHeaders); client.connect(); } else { Log.i(LOG_TAG, "webSocketAddress is null"); } } catch (Exception e) { Log.e(LOG_TAG, "run", e); } } }).start(); } } } }
From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java
public static HttpResponse putDataToUrl(String url, Credentials creds, String acceptTypes, String contentType, String content, Header[] headers) throws IOException { getHttpClient(creds);//from w w w . j av a2 s. c o m //Create the post and add headers HttpPut httpput = new HttpPut(url); StringEntity entity = new StringEntity(content); httpput.setEntity(entity); if (headers != null) { httpput.setHeaders(headers); } if (contentType != null && !contentType.isEmpty()) httpput.addHeader("Content-Type", contentType); if (acceptTypes != null && !acceptTypes.isEmpty()) httpput.addHeader("Accept", acceptTypes); //Send the request and return the response HttpResponse resp = httpclient.execute(httpput, new BasicHttpContext()); return resp; }
From source file:br.com.anteros.android.synchronism.communication.AndroidHttpClient.java
private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override/* ww w .j a v a2 s .c om*/ protected BasicHttpProcessor createHttpProcessor() { // Add interceptor to prevent making requests from main thread. BasicHttpProcessor processor = super.createHttpProcessor(); processor.addRequestInterceptor(sThreadCheckInterceptor); processor.addRequestInterceptor(new CurlLogger()); return processor; } @Override protected HttpContext createHttpContext() { // Same as DefaultHttpClient.createHttpContext() minus the // cookie store. HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes()); context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs()); context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider()); return context; } }; }