List of usage examples for org.apache.http.protocol HttpContext setAttribute
void setAttribute(String str, Object obj);
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
public boolean uploadPics(File[] pics, String text, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); final String ids_string = getMediaIds(pics, twitter); if (ids_string == null) { return false; }//from w ww. j a v a 2 s . c om try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; 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"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/update.json"; 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)); 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); try { try { 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("POST", twitter_endpoint_path); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("media_ids", new StringBody(ids_string)); reqEntity.addPart("status", new StringBody(text)); reqEntity.addPart("trim_user", new StringBody("1")); request2.setEntity(reqEntity); 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); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage()); } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage()); } finally { conn.close(); } } catch (JSONException jsone) { jsone.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (Exception e) { } return true; }
From source file:org.mobicents.client.slee.resource.http.HttpClientResourceAdaptorSbbInterfaceImpl.java
@Override public HttpClientActivity createHttpClientActivity(boolean endOnReceivingResponse, HttpContext context) throws StartActivityException { if (tracer.isFinestEnabled()) { tracer.finest("createHttpClientActivity(endOnReceivingResponse=" + endOnReceivingResponse + ",context=" + context + ")"); }/*ww w . ja v a 2s . c om*/ if (!this.ra.isActive) { throw new IllegalStateException("ra is not in active state"); } // Maintain HttpSession on server side if (context == null) { context = new BasicHttpContext(); } if (context.getAttribute(ClientContext.COOKIE_STORE) == null) { BasicCookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } HttpClientActivity activity = new HttpClientActivityImpl(this.ra, endOnReceivingResponse, context); HttpClientActivityHandle handle = new HttpClientActivityHandle(activity.getSessionId()); // this happens with a tx context this.ra.getResourceAdaptorContext().getSleeEndpoint().startActivitySuspended(handle, activity, ACTIVITY_FLAGS); this.ra.addActivity(handle, activity); if (tracer.isFineEnabled()) { tracer.fine("Started activity " + activity.getSessionId() + ", context is " + context + ", endOnReceivingResponse is " + endOnReceivingResponse); } return activity; }
From source file:org.auraframework.integration.test.util.AuraHttpTestCase.java
/** * Creates HttpContext with httpclient cookie store. Allows cookies to be part of specific request method. * * @return http context/*from w w w. j a va2 s. c o m*/ * @throws Exception */ protected HttpContext getHttpCookieContext() throws Exception { CookieStore cookieStore = getCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); return localContext; }
From source file:io.opentracing.contrib.elasticsearch.common.TracingHttpClientConfigCallback.java
@Override public HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) { httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() { @Override/* w w w . j a v a 2 s. c om*/ public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { Tracer.SpanBuilder spanBuilder = tracer.buildSpan(spanNameProvider.apply(request)) .ignoreActiveSpan().withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT); SpanContext parentContext = extract(request); if (parentContext != null) { spanBuilder.asChildOf(parentContext); } Span span = spanBuilder.start(); SpanDecorator.onRequest(request, span); tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpTextMapInjectAdapter(request)); context.setAttribute("span", span); } }); httpClientBuilder.addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { Object spanObject = context.getAttribute("span"); if (spanObject instanceof Span) { Span span = (Span) spanObject; SpanDecorator.onResponse(response, span); span.finish(); } } }); return httpClientBuilder; }
From source file:org.apache.jena.atlas.web.auth.PreemptiveBasicAuthenticator.java
@Override public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) { this.authenticator.apply(client, httpContext, target); // Enable preemptive basic authentication // For nice layering we need to respect existing auth cache if present AuthCache authCache = (AuthCache) httpContext.getAttribute(ClientContext.AUTH_CACHE); if (authCache == null) authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(this.isProxy ? ChallengeState.PROXY : ChallengeState.TARGET); // TODO It is possible that this overwrites existing cached credentials // so potentially not ideal. authCache.put(new HttpHost(target.getHost(), target.getPort()), basicAuth); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }
From source file:de.geeksfactory.opacclient.apis.BaseApi.java
/** * Perform a HTTP POST request to a given URL * * @param url URL to fetch/*from w ww . j a va 2s . c o m*/ * @param data POST data to send * @param encoding Expected encoding of the response body * @param ignore_errors If true, status codes above 400 do not raise an exception * @param cookieStore If set, the given cookieStore is used instead of the built-in one. * @return Answer content * @throws NotReachableException Thrown when server returns a HTTP status code greater or equal * than 400. */ public String httpPost(String url, HttpEntity data, String encoding, boolean ignore_errors, CookieStore cookieStore) throws IOException { HttpPost httppost = new HttpPost(cleanUrl(url)); httppost.setEntity(data); httppost.setHeader("Accept", "*/*"); HttpResponse response; String html; try { if (cookieStore != null) { // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); response = http_client.execute(httppost, localContext); } else { response = http_client.execute(httppost); } if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) { throw new NotReachableException(response.getStatusLine().getReasonPhrase()); } html = convertStreamToString(response.getEntity().getContent(), encoding); HttpUtils.consume(response.getEntity()); } catch (javax.net.ssl.SSLPeerUnverifiedException e) { logHttpError(e); throw new SSLSecurityException(e.getMessage()); } catch (javax.net.ssl.SSLException e) { // Can be "Not trusted server certificate" or can be a // aborted/interrupted handshake/connection if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) { logHttpError(e); throw new NotReachableException(e.getMessage()); } else { logHttpError(e); throw new SSLSecurityException(e.getMessage()); } } catch (InterruptedIOException e) { logHttpError(e); throw new NotReachableException(e.getMessage()); } catch (UnknownHostException e) { throw new NotReachableException(e.getMessage()); } catch (IOException e) { if (e.getMessage() != null && e.getMessage().contains("Request aborted")) { logHttpError(e); throw new NotReachableException(e.getMessage()); } else { throw e; } } return html; }
From source file:de.geeksfactory.opacclient.apis.BaseApi.java
/** * Perform a HTTP GET request to a given URL * * @param url URL to fetch//from w w w . j av a 2 s. c o m * @param encoding Expected encoding of the response body * @param ignore_errors If true, status codes above 400 do not raise an exception * @param cookieStore If set, the given cookieStore is used instead of the built-in one. * @return Answer content * @throws NotReachableException Thrown when server returns a HTTP status code greater or equal * than 400. */ public String httpGet(String url, String encoding, boolean ignore_errors, CookieStore cookieStore) throws IOException { HttpGet httpget = new HttpGet(cleanUrl(url)); HttpResponse response; String html; httpget.setHeader("Accept", "*/*"); try { if (cookieStore != null) { // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); response = http_client.execute(httpget, localContext); } else { response = http_client.execute(httpget); } if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) { HttpUtils.consume(response.getEntity()); throw new NotReachableException(response.getStatusLine().getReasonPhrase()); } html = convertStreamToString(response.getEntity().getContent(), encoding); HttpUtils.consume(response.getEntity()); } catch (javax.net.ssl.SSLPeerUnverifiedException e) { logHttpError(e); throw new SSLSecurityException(e.getMessage()); } catch (javax.net.ssl.SSLException e) { // Can be "Not trusted server certificate" or can be a // aborted/interrupted handshake/connection if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) { logHttpError(e); throw new NotReachableException(e.getMessage()); } else { logHttpError(e); throw new SSLSecurityException(e.getMessage()); } } catch (InterruptedIOException e) { logHttpError(e); throw new NotReachableException(e.getMessage()); } catch (UnknownHostException e) { throw new NotReachableException(e.getMessage()); } catch (IOException e) { if (e.getMessage() != null && e.getMessage().contains("Request aborted")) { logHttpError(e); throw new NotReachableException(e.getMessage()); } else { throw e; } } return html; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
public String getMediaIds(File[] pics, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); String ids = ""; for (int i = 0; i < pics.length; i++) { File file = pics[i];/* w w w . j a v a 2 s .c om*/ try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; 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"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json"; String twitter_endpoint_host = "upload.twitter.com"; String twitter_endpoint_path = "/1.1/media/upload.json"; 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)); 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); try { try { 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("POST", twitter_endpoint_path); // need to add status parameter to this POST MultipartEntity reqEntity = new MultipartEntity(); FileBody sb_image = new FileBody(file); reqEntity.addPart("media", sb_image); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); System.out.println( "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing..."); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing..."); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); if (jsonresponse.has("errors")) { JSONObject temp_jo = new JSONObject(); temp_jo.put("response_status", "error"); temp_jo.put("message", jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message")); temp_jo.put("twitter_code", jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code")); jsonresponse = temp_jo; } // add it to the media_ids string ids += jsonresponse.getString("media_id_string"); if (i != pics.length - 1) { ids += ","; } conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia HttpException message=" + he.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage()); return null; } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia KeyManagementException message=" + kme.getMessage()); return null; } finally { conn.close(); } } catch (IOException ioe) { ioe.printStackTrace(); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage()); return null; } } catch (Exception e) { return null; } } return ids; }
From source file:com.apigee.sdk.apm.http.impl.client.cache.CachingHttpClient.java
private void setResponseStatus(final HttpContext context, final CacheResponseStatus value) { if (context != null) { context.setAttribute(CACHE_RESPONSE_STATUS, value); }/* w ww . j a v a2s. c om*/ }