List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
From source file:com.novoda.commons.net.httpclient.NovodaHttpClient.java
private NovodaHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override//from www. ja v a2 s . co m 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; } }; }
From source file:br.com.anteros.android.synchronism.communication.AndroidHttpClient.java
private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override/*from w w w.j a v a 2s .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; } }; }
From source file:org.lol.reddit.cache.CacheDownload.java
private void performDownload(final HttpClient httpClient, final HttpRequestBase httpRequest) { if (mInitiator.isJson) httpRequest.setHeader("Accept-Encoding", "gzip"); final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, mInitiator.getCookies()); final HttpResponse response; final StatusLine status; try {/*from w w w . j a v a2s . co m*/ if (mCancelled) { mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled"); return; } response = httpClient.execute(httpRequest, localContext); status = response.getStatusLine(); } catch (Throwable t) { if (t.getCause() != null && t.getCause() instanceof RedirectException && httpRequest.getURI().getHost().endsWith("reddit.com")) { mInitiator.notifyFailure(RequestFailureType.REDDIT_REDIRECT, t, null, "Unable to open a connection"); } else { mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "Unable to open a connection"); } return; } if (status.getStatusCode() != 200) { mInitiator.notifyFailure(RequestFailureType.REQUEST, null, status, String.format("HTTP error %d (%s)", status.getStatusCode(), status.getReasonPhrase())); return; } if (mCancelled) { mInitiator.notifyFailure(RequestFailureType.CANCELLED, null, null, "Cancelled"); return; } final HttpEntity entity = response.getEntity(); if (entity == null) { mInitiator.notifyFailure(RequestFailureType.CONNECTION, null, status, "Did not receive a valid HTTP response"); return; } final InputStream is; final String mimetype; try { is = entity.getContent(); mimetype = entity.getContentType() == null ? null : entity.getContentType().getValue(); } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, status, "Could not open an input stream"); return; } final NotifyOutputStream cacheOs; final CacheManager.WritableCacheFile cacheFile; if (mInitiator.cache) { try { cacheFile = manager.openNewCacheFile(mInitiator, session, mimetype); cacheOs = cacheFile.getOutputStream(); } catch (IOException e) { e.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Could not access the local cache"); return; } } else { cacheOs = null; cacheFile = null; } final long contentLength = entity.getContentLength(); if (mInitiator.isJson) { final InputStream bis; if (mInitiator.cache) { bis = new BufferedInputStream( new CachingInputStream(is, cacheOs, new CachingInputStream.BytesReadListener() { public void onBytesRead(final long total) { mInitiator.notifyProgress(total, contentLength); } }), 8 * 1024); } else { bis = new BufferedInputStream(is, 8 * 1024); } final JsonValue value; try { value = new JsonValue(bis); synchronized (this) { mInitiator.notifyJsonParseStarted(value, RRTime.utcCurrentTimeMillis(), session, false); } value.buildInThisThread(); } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.PARSE, t, null, "Error parsing the JSON stream"); return; } if (mInitiator.cache && cacheFile != null) { try { mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(), session, false, mimetype); } catch (IOException e) { if (e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space"); } else { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found"); } } } } else { if (!mInitiator.cache) { BugReportActivity.handleGlobalError(mInitiator.context, "Cache disabled for non-JSON request"); return; } try { final byte[] buf = new byte[8 * 1024]; int bytesRead; long totalBytesRead = 0; while ((bytesRead = is.read(buf)) > 0) { totalBytesRead += bytesRead; cacheOs.write(buf, 0, bytesRead); mInitiator.notifyProgress(totalBytesRead, contentLength); } cacheOs.flush(); cacheOs.close(); try { mInitiator.notifySuccess(cacheFile.getReadableCacheFile(), RRTime.utcCurrentTimeMillis(), session, false, mimetype); } catch (IOException e) { if (e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.DISK_SPACE, e, null, "Out of disk space"); } else { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Cache file not found"); } } } catch (IOException e) { if (e.getMessage() != null && e.getMessage().contains("ENOSPC")) { mInitiator.notifyFailure(RequestFailureType.STORAGE, e, null, "Out of disk space"); } else { e.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, e, null, "The connection was interrupted"); } } catch (Throwable t) { t.printStackTrace(); mInitiator.notifyFailure(RequestFailureType.CONNECTION, t, null, "The connection was interrupted"); } } }
From source file:org.callimachusproject.client.HttpAuthenticator.java
private AuthState getProxyAuthState(final HttpContext context) { AuthState proxyAuthState = (AuthState) context.getAttribute(HttpClientContext.PROXY_AUTH_STATE); if (proxyAuthState == null) { proxyAuthState = new AuthState(); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); }/*from w w w . j av a 2s.co m*/ return proxyAuthState; }
From source file:com.bytelightning.opensource.pokerface.RequestHandler.java
/** * {@inheritDoc}/*from w w w . ja v a 2 s .c om*/ * Main entry point of a client request into this server. * This method creates a unique id for the request / response transaction, looks for a matching javascript endpoint (which if found is given an opportunity to inspect the request). * If an endpoint is found and it wishes to handle the request, an appropriate <code>HttpAsyncRequestConsumer<ResponseProducer></code> is returned to make that happen. * Otherwise the request (which may have been modified by the endpoint) is asynchronously sent off to a matching remote Target via <code>RequestForTargetConsumer</code>. */ @SuppressWarnings("unchecked") @Override public HttpAsyncRequestConsumer<ResponseProducer> processRequest(HttpRequest request, HttpContext context) { // Create an internal id for this request. String txId = String.format("%08X", idCounter.getAndIncrement()); context.setAttribute("pokerface.txId", txId); boolean requestIsFromScript = false; HttpContext scriptContext = null; ScriptObjectMirror scriptEndpoint = null; RequestLine requestLine = request.getRequestLine(); String uriStr = requestLine.getUri(); int queryPos = uriStr.lastIndexOf('?'); if (queryPos > 0) uriStr = uriStr.substring(0, queryPos); int anchorPos = uriStr.lastIndexOf('#'); // You could have an anchor without a query if (anchorPos > 0) uriStr = uriStr.substring(0, anchorPos); context.setAttribute("pokerface.uripath", uriStr); // See if this is a request for one of our static resources. if (staticFilesPath != null) { String method = requestLine.getMethod(); if (method.equals("GET") || method.equals("HEAD")) { try { Path rsrcPath = staticFilesPath.resolve(uriStr.replaceAll("\\.\\./", "/").substring(1)); if (Files.exists(rsrcPath) && Files.isRegularFile(rsrcPath)) return new RequestForFileConsumer(context, rsrcPath.toFile()); } catch (Exception ex) { Logger.warn("Error resolving URI path", ex); } } } BufferIOController requestBuffer = new BufferIOController(bufferPool); BufferIOController responseBuffer = new BufferIOController(bufferPool); // If script endpoints are configured, look for the closest match (if any). if (scripts != null) { uriStr = uriStr.toLowerCase(); Entry<String, ScriptObjectMirror> entry = scripts.floorEntry(uriStr); if ((entry != null) && uriStr.startsWith(entry.getKey())) { // We found a matching script, so give it an opportunity to inspect the request. StringBuilder sb = new StringBuilder(); RequestLine reqLine = request.getRequestLine(); sb.append(reqLine.getMethod()); sb.append(" "); sb.append(reqLine.getUri()); sb.append(" being inspected by "); String logPrefix = sb.toString(); scriptContext = new BasicHttpContext(context); scriptContext.setAttribute("pokerface.scriptHelper", new ScriptHelperImpl(request, context, bufferPool)); scriptContext.setAttribute("pokerface.endpoints", scripts); scriptContext.setAttribute("pokerface.scriptLogger", ScriptHelper.ScriptLogger); //FIXME: Test out the recursively higher script selection. //FIXME: Add ignore of # directories (don't forget to update the file watcher to ignore them as well) // Call recursively higher (closer to the root) scripts until one is interested. Object scriptResult = null; while (true) { sb.setLength(0); sb.append(logPrefix); String key = entry.getKey(); sb.append(key); if (key.endsWith("/")) sb.append("?"); sb.append(".js"); Logger.info(sb.toString()); scriptEndpoint = entry.getValue(); scriptResult = scriptEndpoint.callMember("inspectRequest", request, scriptContext); scriptResult = transformScriptInspectionResult(request, scriptResult); if (scriptResult == null) { if (uriStr.length() > 1) { int lastSlash = uriStr.lastIndexOf('/', uriStr.length()); if (lastSlash >= 0) { uriStr = uriStr.substring(0, lastSlash + 1); // Add a slash to see if there is a directory script entry = scripts.floorEntry(uriStr); if ((entry != null) && uriStr.startsWith(entry.getKey())) continue; if (lastSlash > 0) { uriStr = uriStr.substring(0, uriStr.length() - 1); // Drop the slash and try again. entry = scripts.floorEntry(uriStr); if ((entry != null) && uriStr.startsWith(entry.getKey())) continue; } } } } break; } // Process the scripts response (if any). if (scriptResult != null) { if (scriptResult instanceof HttpAsyncRequestConsumer<?>) return (HttpAsyncRequestConsumer<ResponseProducer>) scriptResult; else if ((scriptResult instanceof ScriptObjectMirror) && scriptEndpoint.equals(scriptResult)) // The script wants to handle the request itself. return new RequestForScriptConsumer(scriptContext, requestBuffer, new ScriptResponseProducer(scriptEndpoint, request, scriptContext, responseBuffer)); else { // The script wants to pass along a modified Request to the target assert scriptResult instanceof HttpRequest; request = (HttpRequest) scriptResult; requestIsFromScript = true; } } // else no script cared about this request, so just fall through to normal processing. } } // Create a AbsClientRequestConsumer that can proxy to the remote Target. return new RequestForTargetConsumer(scriptContext == null ? context : scriptContext, executor, connPool, patternTargetMapping, requestIsFromScript ? dynamicHostMap : null, request, requestBuffer, responseBuffer, scriptEndpoint); }
From source file:org.callimachusproject.client.HttpAuthenticator.java
private AuthState getTargetAuthState(final HttpContext context) { AuthState targetAuthState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (targetAuthState == null) { targetAuthState = new AuthState(); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); }/*from www .j a va 2 s . c o m*/ return targetAuthState; }
From source file:com.android.mms.service.http.NetworkAwareHttpClient.java
private NetworkAwareHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override//w w w. ja v a 2 s.c o m 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; } }; }
From source file:cl.nic.dte.net.ConexionSii.java
private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII, String token, String urlEnvio, String hostEnvio) throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(urlEnvio); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2))); reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length()))); reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2))); reqEntity.addPart("dvCompany", new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length()))); FileBody bin = new FileBody(archivoEnviarSII); reqEntity.addPart("archivo", bin); httppost.setEntity(reqEntity);// w ww .ja v a2s . c o m BasicClientCookie cookie = new BasicClientCookie("TOKEN", token); cookie.setPath("/"); cookie.setDomain(hostEnvio); cookie.setSecure(true); cookie.setVersion(1); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE"))); HttpResponse response = httpclient.execute(httppost, localContext); HttpEntity resEntity = response.getEntity(); RECEPCIONDTEDocument resp = null; HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http://www.sii.cl/SiiDte"); XmlOptions opts = new XmlOptions(); opts.setLoadSubstituteNamespaces(namespaces); resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts); return resp; }
From source file:com.streamreduce.util.HTTPUtils.java
/** * Opens a connection to the specified URL with the supplied username and password, * if supplied, and then reads the contents of the URL. * * @param url the url to open and read from * @param method the method to use for the request * @param data the request body as string * @param mediaType the media type of the request * @param username the username, if any * @param password the password, if any * @param requestHeaders the special request headers to send * @param responseHeaders save response headers * @return the read string from the//from ww w . j a va 2s .c o m * @throws InvalidCredentialsException if the connection credentials are invalid * @throws IOException if there is a problem with the request */ public static String openUrl(String url, String method, String data, String mediaType, @Nullable String username, @Nullable String password, @Nullable List<Header> requestHeaders, @Nullable List<Header> responseHeaders) throws InvalidCredentialsException, IOException { String response = null; /* Set the cookie policy */ httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); /* Set the user agent */ httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT); HttpContext context = new BasicHttpContext(); HttpRequestBase httpMethod; if (method.equals("DELETE")) { httpMethod = new HttpDelete(url); } else if (method.equals("GET")) { httpMethod = new HttpGet(url); } else if (method.equals("POST")) { httpMethod = new HttpPost(url); } else if (method.equals("PUT")) { httpMethod = new HttpPut(url); } else { throw new IllegalArgumentException("The method you specified is not supported."); } // Put data into the request for POST and PUT requests if (method.equals("POST") || method.equals("PUT") && data != null) { HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) httpMethod; eeMethod.setEntity(new StringEntity(data, ContentType.create(mediaType, "UTF-8"))); } /* Set the username/password if any */ if (username != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); } /* Add request headers if need be */ if (requestHeaders != null) { for (Header header : requestHeaders) { httpMethod.addHeader(header); } } LOGGER.debug("Making HTTP request as " + (username != null ? username : "anonymous") + ": " + method + " - " + url); /* Make the request and read the response */ try { HttpResponse httpResponse = httpClient.execute(httpMethod); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { response = EntityUtils.toString(entity); } int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == 401 || responseCode == 403) { throw new InvalidCredentialsException("The connection credentials are invalid."); } else if (responseCode < 200 || responseCode > 299) { throw new IOException( "Unexpected status code of " + responseCode + " for a " + method + " request to " + url); } if (responseHeaders != null) { responseHeaders.addAll(Arrays.asList(httpResponse.getAllHeaders())); } } catch (IOException e) { httpMethod.abort(); throw e; } return response; }
From source file:com.huashengmi.ui.android.ui.download.http.AndroidHttpClient.java
private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override//from w w w . j ava 2 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; } }; //auto redirect this.delegate.setRedirectHandler(new DefaultRedirectHandler() { @Override public boolean isRedirectRequested(HttpResponse response, HttpContext context) { boolean isRedirect = super.isRedirectRequested(response, context); if (!isRedirect) { int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 301 || responseCode == 302) { return true; } } return isRedirect; } }); }