List of usage examples for org.apache.http.conn.params ConnRouteParams setLocalAddress
public static void setLocalAddress(final HttpParams params, final InetAddress local)
From source file:com.amazonaws.services.dynamodbv2.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config//from w ww. ja va2s . com * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public CloseableHttpAsyncClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive()); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } PoolingClientConnectionManager connectionManager = ConnectionManagerFactory .createPoolingClientConnManager(config, httpClientParams); CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); /* httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton); httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy()); if (config.getConnectionMaxIdleMillis() > 0) { httpClient.setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy( config.getConnectionMaxIdleMillis())); }*/ if (config.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress()); } try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = config.getApacheHttpClientConfig().getSslSocketFactory(); if (sf == null) { sf = new SdkTLSSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to access default SSL context", e); } /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); //httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); /*if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } // Add a request interceptor that sets up proxy authentication pre-emptively if configured if (config.isPreemptiveBasicProxyAuth()){ httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0); } } */ /* Accept Gzip response if configured */ if (config.useGzip()) { /* httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName() .equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity( response.getEntity())); return; } } } } } });*/ } return httpClient; }
From source file:com.amazonaws.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config//from w w w .j a v a 2 s . co m * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive()); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } final SSLContext sslContext = createSSLContext(config); SSLSocketFactory sslSocketFactory = config.getApacheHttpClientConfig().getSslSocketFactory(); if (sslSocketFactory == null) { sslSocketFactory = new SdkTLSSocketFactory(sslContext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } PoolingClientConnectionManager connectionManager = ConnectionManagerFactory .createPoolingClientConnManager(config, httpClientParams, sslSocketFactory); SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams); httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton); httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy()); if (config.getConnectionMaxIdleMillis() > 0) { httpClient .setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(config.getConnectionMaxIdleMillis())); } if (config.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress()); } Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); Scheme https = new Scheme("https", 443, sslSocketFactory); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } // Add a request interceptor that sets up proxy authentication pre-emptively if configured if (config.isPreemptiveBasicProxyAuth()) { httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0); } } /* Accept Gzip response if configured */ if (config.useGzip()) { httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); } return httpClient; }
From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java
/**Uploads the data, returns the HTTP result code*/ public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender, Partner receiver, URL receiptURL) { String ediintFeatures = "multiple-attachments, CEM"; //set the http connection/routing/protocol parameter HttpParams httpParams = new BasicHttpParams(); if (connectionParameter.getConnectionTimeoutMillis() != -1) { HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis()); }//w w w . j a v a 2 s.c om if (connectionParameter.getSoTimeoutMillis() != -1) { HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis()); } HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck()); if (connectionParameter.getHttpProtocolVersion() == null) { //default settings: HTTP 1.1 HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) { HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0); } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) { HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); } HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue()); HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent()); if (connectionParameter.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress()); } int status = -1; HttpPost filePost = null; DefaultHttpClient httpClient = null; try { ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams); httpClient = new DefaultHttpClient(clientConnectionManager, httpParams); //some ssl implementations have problems with a session/connection reuse httpClient.setReuseStrategy(new NoConnectionReuseStrategy()); //disable SSL hostname verification. Do not confuse this with SSL trust verification! SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry() .get("https").getSocketFactory(); sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //determine the receipt URL if it is not set if (receiptURL == null) { //async MDN requested? if (message.isMDN()) { if (this.runtimeConnection == null) { throw new IllegalArgumentException( "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN"); } MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); AS2MessageInfo relatedMessageInfo = messageAccess .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId()); receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL()); } else { receiptURL = new URL(receiver.getURL()); } } filePost = new HttpPost(receiptURL.toExternalForm()); filePost.addHeader("as2-version", "1.2"); filePost.addHeader("ediint-features", ediintFeatures); filePost.addHeader("mime-version", "1.0"); filePost.addHeader("recipient-address", receiptURL.toExternalForm()); filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">"); filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification())); filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification())); String originalFilename = null; if (message.getPayloads() != null && message.getPayloads().size() > 0) { originalFilename = message.getPayloads().get(0).getOriginalFilename(); } if (originalFilename != null) { String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename); filePost.addHeader("subject", subject); //update the message infos subject with the actual content if (!message.isMDN()) { ((AS2MessageInfo) message.getAS2Info()).setSubject(subject); //refresh this in the database if it is requested if (this.runtimeConnection != null) { MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection); access.updateSubject((AS2MessageInfo) message.getAS2Info()); } } } else { filePost.addHeader("subject", message.getAS2Info().getSubject()); } filePost.addHeader("from", sender.getEmail()); filePost.addHeader("connection", "close, TE"); //the data header must be always in english locale else there would be special //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after //RFC 4130 DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US); filePost.addHeader("date", format.format(new Date())); String contentType = null; if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) { contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m"; } else { contentType = message.getContentType(); } filePost.addHeader("content-type", contentType); //MDN header, this is always the way for async MDNs if (message.isMDN()) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.mdn.async", new Object[] { message.getAS2Info().getMessageId(), receiptURL }), message.getAS2Info()); } filePost.addHeader("server", message.getAS2Info().getUserAgent()); } else { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); //outbound AS2/CEM message if (messageInfo.requestsSyncMDN()) { if (this.logger != null) { if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.cem.sync", new Object[] { messageInfo.getMessageId(), receiver.getURL() }), messageInfo); } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.msg.sync", new Object[] { messageInfo.getMessageId(), receiver.getURL() }), messageInfo); } } } else { //Message with ASYNC MDN request if (this.logger != null) { if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.cem.async", new Object[] { messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }), messageInfo); } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) { this.logger.log(Level.INFO, this.rb.getResourceString("sending.msg.async", new Object[] { messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }), messageInfo); } } //The following header indicates that this requests an asnc MDN. //When the header "receipt-delivery-option" is present, //the header "disposition-notification-to" serves as a request //for an asynchronous MDN. //The header "receipt-delivery-option" must always be accompanied by //the header "disposition-notification-to". //When the header "receipt-delivery-option" is not present and the header //"disposition-notification-to" is present, the header "disposition-notification-to" //serves as a request for a synchronous MDN. filePost.addHeader("receipt-delivery-option", sender.getMdnURL()); } filePost.addHeader("disposition-notification-to", sender.getMdnURL()); //request a signed MDN if this is set up in the partner configuration if (receiver.isSignedMDN()) { filePost.addHeader("disposition-notification-options", messageInfo.getDispositionNotificationOptions().getHeaderValue()); } if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) { filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\""); } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) { filePost.addHeader("content-disposition", "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\""); } } int port = receiptURL.getPort(); if (port == -1) { port = receiptURL.getDefaultPort(); } filePost.addHeader("host", receiptURL.getHost() + ":" + port); InputStream rawDataInputStream = message.getRawDataInputStream(); InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize()); postEntity.setContentType(contentType); filePost.setEntity(postEntity); if (connectionParameter.getProxy() != null) { this.setProxyToConnection(httpClient, message, connectionParameter.getProxy()); } this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN()); this.updateUploadHttpHeader(filePost, receiver); HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(), receiptURL.getProtocol()); BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context. Without this a HTTP authentication will not be sent BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext); rawDataInputStream.close(); this.responseData = this.readEntityData(httpResponse); if (httpResponse != null) { this.responseStatusLine = httpResponse.getStatusLine(); status = this.responseStatusLine.getStatusCode(); this.responseHeader = httpResponse.getAllHeaders(); } for (Header singleHeader : filePost.getAllHeaders()) { if (singleHeader.getValue() != null) { this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue()); } } //accept all 2xx answers //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed. //SC_CREATED Status code (201) indicating the request succeeded and created a new resource on the server. //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return. //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server. //SC_OK Status code (200) indicating the request succeeded normally. //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent. //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource. if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION && status != HttpServletResponse.SC_RESET_CONTENT && status != HttpServletResponse.SC_PARTIAL_CONTENT) { if (this.logger != null) { this.logger .severe(this.rb.getResourceString("error.httpupload", new Object[] { message.getAS2Info().getMessageId(), URLDecoder.decode( this.responseStatusLine == null ? "" : this.responseStatusLine.getReasonPhrase(), "UTF-8") })); } } } catch (Exception ex) { if (this.logger != null) { StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId()); errorMessage.append(": MessageHTTPUploader.performUpload: ["); errorMessage.append(ex.getClass().getSimpleName()); errorMessage.append("]"); if (ex.getMessage() != null) { errorMessage.append(": ").append(ex.getMessage()); } this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info()); } } finally { if (httpClient != null && httpClient.getConnectionManager() != null) { //shutdown the HTTPClient to release the resources httpClient.getConnectionManager().shutdown(); } } return (status); }
From source file:com.android.development.Connectivity.java
private void onBoundHttpRequest() { NetworkInterface networkInterface = null; try {//from w w w . j ava 2 s .c om networkInterface = NetworkInterface.getByName("rmnet0"); Log.d(TAG, "networkInterface is " + networkInterface); } catch (Exception e) { Log.e(TAG, " exception getByName: " + e); return; } if (networkInterface != null) { Enumeration inetAddressess = networkInterface.getInetAddresses(); while (inetAddressess.hasMoreElements()) { Log.d(TAG, " inetAddress:" + ((InetAddress) inetAddressess.nextElement())); } } HttpParams httpParams = new BasicHttpParams(); if (networkInterface != null) { ConnRouteParams.setLocalAddress(httpParams, networkInterface.getInetAddresses().nextElement()); } HttpGet get = new HttpGet("http://www.bbc.com"); HttpClient client = new DefaultHttpClient(httpParams); try { HttpResponse response = client.execute(get); Log.d(TAG, "response code = " + response.getStatusLine()); } catch (Exception e) { Log.e(TAG, "Exception = " + e); } }