use of org.apache.http.protocol.BasicHttpContext in project Fling by entertailion.
the class RampClient method launchApp.
public void launchApp(String app, DialServer dialServer) {
this.app = app;
this.isChromeCast = app.equals(FlingFrame.CHROMECAST);
this.dialServer = dialServer;
this.activityId = UUID.randomUUID().toString();
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;
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);
}
String response = EntityUtils.toString(httpResponse.getEntity());
Log.d(LOG_TAG, "get response=" + response);
parseXml(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(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);
if (isChromeCast) {
// httpPost.setEntity(new StringEntity("v=release-d4fa0a24f89ec5ba83f7bf3324282c8d046bf612&id=local%3A1&idle=windowclose"));
httpPost.setEntity(new StringEntity("v=release-d4fa0a24f89ec5ba83f7bf3324282c8d046bf612&id=local%3A1"));
}
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(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");
// oops, something went wrong
return;
}
// get the websocket URL
String webSocketAddress = null;
// "http://192.168.0.17:8008/connection/YouTube"
httpPost = new HttpPost(connectionServiceUrl);
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\":\"" + app + "\", \"senderId\":\"" + senderId + "\"}}"));
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());
}
// http://code.google.com/p/json-simple/
JSONParser parser = new JSONParser();
try {
// {"URL":"ws://192.168.0.17:8008/session?33","pingInterval":0}
Object obj = parser.parse(new StringReader(response));
JSONObject jsonObject = (JSONObject) obj;
webSocketAddress = (String) jsonObject.get("URL");
Log.d(LOG_TAG, "webSocketAddress: " + webSocketAddress);
// TODO
long pingInterval = (Long) jsonObject.get("pingInterval");
} catch (Exception e) {
Log.e(LOG_TAG, "parse JSON", e);
}
}
} else {
Log.i(LOG_TAG, "no post response");
return;
}
// Make a web socket connection for doing RAMP
// to control media playback
this.started = false;
this.closed = false;
this.gotStatus = false;
if (webSocketAddress != null) {
// https://github.com/TooTallNate/Java-WebSocket
URI uri = URI.create(webSocketAddress);
rampWebSocketClient = new RampWebSocketClient(uri, this);
new Thread(new Runnable() {
public void run() {
Thread t = new Thread(rampWebSocketClient);
t.start();
try {
t.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
rampWebSocketClient.close();
}
}
}).start();
} else {
Log.i(LOG_TAG, "webSocketAddress is null");
}
} catch (Exception e) {
Log.e(LOG_TAG, "launchApp", e);
}
}
use of org.apache.http.protocol.BasicHttpContext in project ignition by mttkay.
the class IgnitedHttpRequestBase method send.
@Override
public IgnitedHttpResponse send() throws ConnectException {
IgnitedHttpRequestRetryHandler retryHandler = new IgnitedHttpRequestRetryHandler(maxRetries);
// tell HttpClient to user our own retry handler
httpClient.setHttpRequestRetryHandler(retryHandler);
HttpContext context = new BasicHttpContext();
// Grab a coffee now and lean back, I'm not good at explaining stuff. This code realizes
// a second retry layer on top of HttpClient. Rationale: HttpClient.execute sometimes craps
// out even *before* the HttpRequestRetryHandler set above is called, e.g. on a
// "Network unreachable" SocketException, which can happen when failing over from Wi-Fi to
// 3G or vice versa. Hence, we catch these exceptions, feed it through the same retry
// decision method *again*, and align the execution count along the way.
boolean retry = true;
IOException cause = null;
while (retry) {
try {
return httpClient.execute(request, this, context);
} catch (IOException e) {
cause = e;
retry = retryRequest(retryHandler, cause, context);
} catch (NullPointerException e) {
// there's a bug in HttpClient 4.0.x that on some occasions causes
// DefaultRequestExecutor to throw an NPE, see
// http://code.google.com/p/android/issues/detail?id=5255
cause = new IOException("NPE in HttpClient" + e.getMessage());
retry = retryRequest(retryHandler, cause, context);
} finally {
// if timeout was changed with this request using withTimeout(), reset it
if (timeoutChanged) {
ignitedHttp.setConnectionTimeout(oldConnTimeout);
ignitedHttp.setSocketTimeout(oldSocketTimeout);
}
}
}
// no retries left, crap out with exception
ConnectException ex = new ConnectException();
ex.initCause(cause);
throw ex;
}
use of org.apache.http.protocol.BasicHttpContext in project newsrob by marianokamp.
the class Asset method loadTextFromUrl.
static Map<String, String> loadTextFromUrl(NewsRobHttpClient httpClient, URL pageUrl, long started, Job job, Context context) throws DownloadException, DownloadCancelledException, URISyntaxException, SocketException, SocketTimeoutException, DownloadTimedOutException {
Map<String, String> returnValues = new HashMap<String, String>(2);
CharSequence result = null;
HttpResponse response;
HttpContext localContext = new BasicHttpContext();
try {
HttpGet loadRequest = new HttpGet(pageUrl.toURI());
response = httpClient.executeZipped(loadRequest, localContext);
} catch (IOException e) {
throw new DownloadException("Problem during download of " + pageUrl + ".", e);
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
throw new WrongStatusException(pageUrl, statusCode);
String newUri = extractUriFromHttpContext(localContext);
if (!pageUrl.toString().equals(newUri)) {
PL.log("WPDD Downloader: Changed page's url after redirect from " + pageUrl + " to " + newUri + ".", context);
try {
pageUrl = new URL(newUri);
} catch (MalformedURLException e) {
e.printStackTrace();
// keep the existing pageUrl
}
}
try {
String charsetName = null;
for (HeaderElement he : response.getEntity().getContentType().getElements()) {
NameValuePair nvp = he.getParameterByName("charset");
if (nvp != null) {
charsetName = nvp.getValue();
break;
}
}
result = U2.readInputStreamIntoString(NewsRobHttpClient.getUngzippedContent(response.getEntity(), context), charsetName, started, job);
response.getEntity().consumeContent();
} catch (IOException e) {
throw new DownloadException("Problem during reading of InputStream when loading " + pageUrl + ".", e);
}
returnValues.put("url", pageUrl.toExternalForm());
returnValues.put("content", result.toString());
return returnValues;
}
use of org.apache.http.protocol.BasicHttpContext in project Java-readability by basis-technology-corp.
the class HttpPageReader method readPage.
/**
* {@inheritDoc}
*/
@Override
public String readPage(String url) throws PageReadException {
LOG.info("Reading " + url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpGet get = new HttpGet(url);
InputStream response = null;
HttpResponse httpResponse = null;
try {
try {
httpResponse = httpclient.execute(get, localContext);
int resp = httpResponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK != resp) {
LOG.error("Download failed of " + url + " status " + resp + " " + httpResponse.getStatusLine().getReasonPhrase());
return null;
}
String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());
return readContent(httpResponse.getEntity().getContent(), respCharset);
} finally {
if (response != null) {
response.close();
}
if (httpResponse != null && httpResponse.getEntity() != null) {
httpResponse.getEntity().consumeContent();
}
}
} catch (IOException e) {
LOG.error("Download failed of " + url, e);
throw new PageReadException("Failed to read " + url, e);
}
}
use of org.apache.http.protocol.BasicHttpContext in project wildfly by wildfly.
the class XFrameOptionsHeaderTestCase method checkURLForHeader.
private void checkURLForHeader(URL url, String headerName, String expectedHeaderValue) throws URISyntaxException, IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(createCredentialsProvider(url)).build()) {
HttpContext httpContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url.toURI());
HttpResponse response = httpClient.execute(httpGet, httpContext);
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Wrong response code: " + statusCode + " for url '" + url.toString() + "'.", HttpURLConnection.HTTP_OK, statusCode);
Header[] headers = response.getHeaders(headerName);
assertNotNull("Unexpected behaviour of HttpResponse#getHeaders() returned null!", headers);
assertTrue("There is no '" + headerName + "' header present! Headers present: " + Arrays.toString(response.getAllHeaders()), headers.length > 0);
for (Header header : headers) {
if (header.getValue().equals(expectedHeaderValue)) {
return;
}
}
fail("No header '" + headerName + "' with value '" + expectedHeaderValue + "' found!");
}
}
Aggregations