Menu
  • HOME
  • TAGS

Creating a HTTP connecting and keeping it open to recieve data

java,http,apache-httpclient-4.x

With traditional HTTP technology you can only do polling, which means you request "do you have more data" from the server. The server than can wait for some time when it has no data (this is called "long polling"). This should be a short time so it works with stuff...

how to implement long-link or half-long-link by HttpClient?

apache-httpclient-4.x,android-async-http

If your so-called "long-link" or "half-long-link" means "keep-alive", then I thought I got a solution. There is a header called "Connection" which has two arguments to be selected: "Keep-Alive" or "close". In http 1.0, it's "close" by default. But in Http 1.1, "Keep-Alive" is the default value. So, if you...

Unable to download image from Google Cloud Storage url with Android

java,android,google-cloud-storage,httpurlconnection,apache-httpclient-4.x

As stated here, HttpClient seems not to support underscores for hostname. Also, there is a long discussion about the use of underscores on domain names and hostnames....

Why is the constant HTTP.UTF_8 deprecated?

java,apache-httpclient-4.x

Since Java 7, Java provides the StandardCharsets class for getting the Charset object for a few standard character sets. These are: ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16BE, and UTF-16LE. That's the alternative. There's no longer a point in re-declaring the String name of the character set in an HTTP class....

DefaultHttpClient blocking different threads

android,multithreading,apache-httpclient-4.x

Are you sure it's the HttpClient and not the AsyncTask that can only have one running instance? If I recall correctly, the default threadpool for AsyncTask (unfortunately) has 1 thread associated with it which means only 1 active AsyncTask can run at any given time. To fix, you can try...

How to force Apache HttpClient / HttpConnection to absolutely close tcp connection?

java,sockets,connection,apache-httpclient-4.x,forceclose

RequestConfig has helped. Now it looks like all the connections are discarded in specified limits. RequestConfig config= RequestConfig.custom() .setCircularRedirectsAllowed(false) .setConnectionRequestTimeout(4000) .setConnectTimeout(4000) .setMaxRedirects(0) .setRedirectsEnabled(false) .setSocketTimeout(4000) .setStaleConnectionCheckEnabled(true).build(); request.setConfig(config); ...

Using HttpAsyncClients: keep connection alive for long time

java,http,apache-httpclient-4.x

The re-use of the same instance of HttpAsyncClient is highly recommended. HttpAsyncClient will not get 'stale'. One only needs to close HttpAsyncClient once there are no more requests to be executed (for instance, in case of application shut down).

Getting results of WFS request to GeoServer as UTF-8

java,utf-8,apache-httpclient-4.x,geoserver

Instead of passing in a BasicResponseHandler, use the HttpClient.execute(HttpUriRequest) method which returns a HttpResponse and then use EntityUtils.toString(HttpEntity, "UTF-8"), pseudo: HttpResponse r = httpClient.execute(httPost) String utf8encodedEntity = EntityUtils.toString(r.getEntity(), "UTF-8"); ...

How to configure the number of allowed pending requests in Apache async client

java,apache,httpclient,apache-httpclient-4.x

Apache HttpAsyncClient maintains an unbounded request execution queue and does not attempt to limit the number of pending requests. Various applications may or may not want to throttle request rate and there is no easy way to satisfy them all. One can however fairly easily throttle the number of concurrent...

Manipulating request entity using HttpRequestInterceptor in Apache HttpClient

apache,apache-httpclient-4.x

This should fix the problem if(request instanceof HttpEntityEnclosingRequest) { HttpEntity rqEntity = ((HttpEntityEnclosingRequest) request).getEntity(); ...

How to force the http client to not handle the authentication challenges automatically in httpClient 4.3.x?

java,httpclient,apache-httpclient-4.x

I think I got it. I guess it can be done by setting the setDoAuthentication() method to false in the requestConfig for httpClient.

How to execute url which has xml data as query parameter through Apache HttpClient?

java,http-post,apache-httpclient-4.x,apache-commons-httpclient

Honestly, I don't think you want to try and pass XML through your URI. There are several things to consider. One, some servers will block long URIs (Google first result: http://www.checkupdown.com/status/E414.html ). Next, you would want to "encode" the URI so it escapes all of your chars that are not...

Use of non-ascii credentials not working in httpclient 4.3.x

java,character-encoding,apache-httpclient-4.x

Custom charset encoding is applicable to some auth schemes (such Basic and Digest) and not applicable to others. Global custom auth charset parameter was a bad idea Credentials charset has to be configured on a per scheme basis using custom auth scheme factories Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8))...

Websphere httpclient NoSuchMethodError org.apache.http.conn.Scheme

java,websphere,classloader,apache-httpclient-4.x

You need both settings - isolated shared library and PARENT_LAST classloader setting to use your own httpclient libraries. PARENT_LAST is required to override classes provided by the server....

HTTPs connection by apache httpclient 4.4

java,apache,apache-httpclient-4.x

In this page there is a solution about this subject. One of the solution is updating the CACERT file in the your JRE_HOME/lib directory.For that you can look here. And the other solution is overriding the check and accept an untrusted certificate. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()...

Mockito: returning the passed parameter

java,mocking,mockito,apache-httpclient-4.x

I found a solution to my own problem: final MutableWrapper<String> stringWrapper = new MutableWrapper<>(); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { stringWrapper.wrap(invocation.getArgumentAt(1, String.class)); return null; } }).when(request).setHeader(Matchers.eq(HEADER), Matchers.anyString()); Mockito.doAnswer(new Answer<Header>() { @Override public Header answer(InvocationOnMock invocation) throws Throwable { Header header =...

What does setDefaultMaxPerRoute and setMaxTotal mean in HttpClient?

java,apache-httpclient-4.x

Some parameters are explained at http://hc.apache.org/httpclient-3.x/preference-api.html Others must be gleaned from the source. setMaxTotal The maximum number of connections allowed across all routes. setDefaultMaxPerRoute The maximum number of connections allowed for a route that has not been specified otherwise by a call to setMaxPerRoute. Use setMaxPerRoute when you know the...

Extracting gzip data from Apache-httpclient without decompression

apache-httpclient-4.x

CloseableHttpClient client = HttpClients.custom() .disableContentCompression() .build(); ...

Apache HttpClient DigestAuth - 401, Unauthorized. But Credentials are okay

java,apache-httpclient-4.x,http-authentication,http-status-code-401,digest-authentication

It may or may not be the reason, but the scope of credentials is wrong. The AuthScope constructor takes a host name, not a URL as the first parameter. credentialsProvider.setCredentials( new AuthScope("myurl.xx",80), new UsernamePasswordCredentials(username,pw)); ...

Error creating a bean in Spring Mvc Web Application

spring,java-ee,spring-mvc,model-view-controller,apache-httpclient-4.x

I figured out the problem. Problem was the version of HTTPClient. I guess they changed the directories in the new version. In version 3 HttpMethod class was under org.apache.common.httpclient and in version 4 its under org.apache.httpclient. so after downloading the older version i was able to fix the problem. Thanks...

How to set outgoing Host header from Camel http4 proxy

apache-camel,apache-httpclient-4.x

You can setup the HttpContext instance by using the httpContext option like this. Please make sure the HttpContext instance is bind with "customerContext" in the Registry. http4://localhost:8081?httpBindingRef=customBinding&httpClientConfigurerRef=customConfigurer&httpContext=#customContext ...

Uploading to the Google Publisher API

android,scala,apache-httpclient-4.x

As far as the curl goes - It was legitimately an invalid APK. This threw me off because it would upload fine on the web interface. I got a newer version of my apk out and it worked. As for the scala, it was the fact that it was sending...

Making Apache HttpClient 4.3 work with sslSocketFactory/HostnameVerifier

java,ssl,ssl-certificate,apache-commons,apache-httpclient-4.x

I have no idea how Verifier is implemented but this code snippet demonstrates how one can create a custom hostname verifier none of those shipped with HttpClient fits their needs KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream in = new FileInputStream(new File("C:\\Program Files (x86)\\Java\\jre7\\bin\\my.keystore")); try { ks.load(in, "blahblah".toCharArray()); } finally { in.close();...

'Improperly formatted request' error after switching from Commons HttpClient to HttpComponents

java,migration,apache-httpclient-4.x,apache-commons-httpclient

Try using 'browser compatible' mode instead of 'strict' when constructing the request entity with MultipartEntityBuilder UPDATE 1: "Content-Type: multipart/form-data[\r][\n]" This is clearly wrong (boundary attribute is missing) and likely to be reason for the request being rejected. Please remove this line and try again post.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.MULTIPART_FORM_DATA.getMimeType()); ...

HttpClient java.net.UnknownHostException exception when the CURL command passes

java,apache-httpclient-4.x

Read the JavaDoc for HttpHost: Parameters: hostname - the hostname (IP or DNS name) So you should use just (omit the protocol and context): HttpHost target = new HttpHost( "<JENKINS_URL>" ); and then HttpGet the /api/json part. Cheers,...

setMaxTotal and setDefaultMaxPerRoute in HttpClient?

java,spring,connection-pooling,apache-httpclient-4.x,resttemplate

The builder parameters are used to construct a default pooling connection manager if you don't provide one. So in your example the sets on the builder are redundant. See HttpClientBuilder (sorry I had to snip this enormous method down a lot): public CloseableHttpClient build() { ... snip ... HttpClientConnectionManager connManagerCopy...

Configuring SSL in Apache HttpAsyncClient

apache,ssl,apache-httpclient-4.x,apache-httpcomponents

(I run in very similar problem recently (on Android) but I guess you are making the same error as I did.) When you set a connection manager explicitly : builder.setConnectionManager(cm) the sslContext is ignored. What you can do is inject your SSLContext in the PoolingNHttpClientConnectionManager. To do so, you can...

java httpclient 4.x performance guide to resolve issue

java,performance,apache-httpclient-4.x

The main recommendation is still the same as it was for 3.1 Please DO re-use the HttpClient instance! HttpClient instances are very expensive. By throwing it away not only you throw away the instance itself, you also throw away the SSL context, the connection manager, and all persistent connections that...

Apache HTTP Client: build simulator using multithreaded environment

java,multithreading,apache-httpclient-4.x,java.util.concurrent

You can toggle re-use of connections within the pool using the builder's setConnectionReuseStrategy. The DefaultConnectionReuseStrategy will re-use connections whenever possible, but the NoConnectionReuseStrategy will close all connections returned to the pool. I used these connection re-use strategies in reverse: in production no re-use was set (to ensure proper load-balancing -...

Trying to send HTTP Client image and string to API - compile error = multipartentitybuilder() is not public cannot be accessed from outside package

apache,android-activity,apache-httpclient-4.x,multipart,androidhttpclient

I ended up not needing MultiPartEntityBuilder -- could do with MultiPartEntity. thanks

How to use HttpClient to keep login state for furture process after the app was restarted?

java,android,apache,apache-httpclient-4.x

What you need to do is save the user's data to the PreferenceManager when the user login for the first time and when the app quit and then restarted you can then check the PreferenceManager if it have some data or not before you do some action. click here for...

Block Apache HttpClient 4 from accessing a specific route

java,http,apache-httpclient-4.x

final Set<HttpHost> sitesToBlock = new HashSet<HttpHost>(); sitesToBlock.add(new HttpHost("example.com", 80)); DefaultRoutePlanner routePlanner = new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE) { @Override public HttpRoute determineRoute( final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException { final HttpRoute route = super.determineRoute(host, request, context); if (sitesToBlock.contains(route.getTargetHost())) { throw new HttpException("Connection to " + host + "...

Is apache asyncClient actual async or it uses thread behind the scene

java,apache,http,asynchronous,apache-httpclient-4.x

Apache HttpAsyncClient is based on Apache HttpCore NIO, which is a low level HTTP transport library based on Java NIO.

How to solve org.apache.http.NoHttpResponseException

java,apache-httpclient-4.x

Finally figured it out on my own. If the previous response gives header, "connections=close", next request always gets this exception. So, when seeing this header, put 2 more lines conManager.closeExpiredConnections(); conManager.closeIdleConnections(0, TimeUnit.SECONDS); to let connection manager close the connection so that the connection won't be used by the next request....

Apache httpclient: why doesn't retry when timeout

java,apache-httpclient-4.x

It won't retry if it's timeout. What's the reason? Why should it? Timeouts usually defines a maximum period of inactivity between two consecutive operations. Why should the request be retried if it times out in the first place? If you are willing to wait longer for the operation to...

Premature end of Content-Length delimited message body (expected:

java,apache-httpclient-4.x

The problem appears to be on the server-side, not in the client code you've pasted. The server claimed that the content contained 203856 bytes but only sent 1070....

How to print/log an Apache HttpClient request query string

java,apache-httpclient-4.x

Not sure if you've tried it, but the HTTP Client library has some logging settings you can enable. http://hc.apache.org/httpcomponents-client-4.3.x/logging.html...

What Resources Will I Free Up By Closing a CloseableHttpClient?

java,apache-httpclient-4.x

This depends on CloseableHttpClient instance. Generally, CloseableHttpClient#close makes sure that the underlying connection pool is shut down and persistent connections kept alive are all closed out. Caching CloseableHttpClient instances bound to a persistent store may also clean up cache content.

How do i set basic authentication using apache httpClient

java,apache-httpclient-4.x,apache-commons-httpclient

Update: Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("UserName", "[email protected]".toCharArray()); } }); You also need to set other header properties: (example) response.addHeader("Access-Control-Allow-Methods", ""); response.setHeader("Access-Control-Allow-Origin", "http://podcastpedia.org"); //allows CORS requests only coming from podcastpedia.org Code to add a basic authentication property to an httpURLConnection String basic = "Basic " +...

NoSuchFieldError INSTANCE at org.apache.http.impl.io.DefaultHttpRequestWriterFactory

java,gradle,apache-httpclient-4.x

org.apache.httpcomponents:httpcore:4.1 -> 4.3.3 means 4.1 is the requested version, which is resolved to 4.3.3 by conflict resolution. Executing something like gradle -q dependencyInsight --configuration compile --dependency httpcore should give you more insight on this. You should check the build output, and see what jars are actually packaged with your app....

Integrating persistent caching into Apache Httpclient with EhCache

java,caching,ehcache,apache-httpclient-4.x,http-caching

Beaware: Ehcache's LOCALRESTARTABLE strategy requires Enterprise license. Well this, would work perfectly, if I had a commercial license of EhCache, which I don't. Had I known that, I wouldn't have gone through the trouble. Digging further using google and the documentation of Httpclient, the first thing you need to do...

How do I set SSL protocol version in java? And how do I know which one? javax.net.ssl.SSLException: Received fatal alert: protocol_version

java,ssl,apache-httpclient-4.x,hubic-api

I see from the debug that Java does a TLS1.2 handshake instead of the more common SSLv23 handshake: main, WRITE: TLSv1.2 Handshake, length = 225 [Raw write]: length = 230 0000: 16 03 03 00 ^^^^^ - TLS1.2 (SSL3.3) The server itself can do only TLS1.0 and fails to just...

Apache HttpClient Session not working

java,session,apache-httpclient-4.x

Sorry, rookie mistake on my part. No wonder it wasn't working, the second request in my question (the GET, after logging in) wasn't actually passing in the httpContext object that contains the cookies.

How to stream response body with apache HttpClient

java,httpclient,apache-httpclient-4.x,apache-commons-httpclient

EDIT 2 So, if u not comfortable with threads/runnables/Handlers and not comfortable with android AsyncTask, I would just go straight to HttpUrlConnection (drop the entire excercise with apacheHttpClient because , basically googl says that HttpUrlConn will support stream'd response and it does work!) It may not be as easy instrumenting...

HttpClient error

java,android,apache-httpclient-4.x

you can not make it in the UI thread Here is an example using AsyncTask EditText host = (EditText)findViewById(R.id.editText); EditText port = (EditText)findViewById(R.id.editText2); EditText community = (EditText)findViewById(R.id.editText3); String url = "http://192.168.0.102/za/getstatus.php?host=" + host.getText().toString() + "&port=" + port.getText().toString() + "&com=" + community.getText().toString() + "&oid=" + 2 + "&port1=" + 2; new...

How to update the settings of an HttpClient in httpclient 4.3+?

java,spring,httpclient,apache-httpclient-4.x

do something I have not proposed yet? My recommendation would be to re-think the entire approach. One should not be removing / adding protocol interceptors at runtime but rather should be making use of HttpContext instance to update request execution context and pass configuration to protocol interceptors http://hc.apache.org/httpcomponents-core-4.4.x/tutorial/html/fundamentals.html#d5e306 http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fundamentals.html#d5e223...

UnknownHostException from Java but host resolves with Ping/nslookup/curl

java,networking,jboss,dns,apache-httpclient-4.x

This is most likely a network management, change / configuration management or general system administration problem rather than a programming problem. It was working before without adding that entry but all of a sudden it stopped working. One approach is to try to figure out what changed to cause it...

How to set timeout for each request using Apache httpclient 4.* with PoolingHttpClientConnectionManager?

java,apache-httpclient-4.x,connection-timeout

HttpGet get1 = new HttpGet("http://hosta/"); RequestConfig config1 = RequestConfig.custom().setSocketTimeout(10000).build(); get1.setConfig(config1); HttpGet get2 = new HttpGet("http://hostb/"); RequestConfig config2 = RequestConfig.custom().setSocketTimeout(5000).build(); get2.setConfig(config2); ...

How can I get cookie from httpclient?

android,cookies,apache-httpclient-4.x

CloseableHttpClient httpclient = HttpClients.createDefault(); HttpClientContext context = HttpClientContext.create(); BasicCookieStore cookieStore = new BasicCookieStore(); context.setCookieStore(cookieStore); HttpGet httpget = new HttpGet("https://host/stuff"); CloseableHttpResponse response = httpclient.execute(httpget); try { List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString());...

WWW-Authentication / NTLM Negotiate using HttpClient with current user credentials

java,iis,apache-httpclient-4.x,www-authenticate

You might want to try out HttpClient 4.4 (to be released as GA soon). It supports native Windows Negotiate, Kerberos and NTLM via SSPI through JNA when running on Windows OS. Please note this feature is still considered experimental. Your mileage may vary. http://hc.apache.org/httpcomponents-client-4.4.x/httpclient-win/examples/org/apache/http/examples/client/win/ClientWinAuth.java...

HttpClient 4.3.x, fixing deprecated code to use current HttpClient implementations

java,apache-httpclient-4.x

HttpClientBuilder builder = HttpClientBuilder.create(); SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslConnectionFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);...

Code getting stuck at http execute

java,apache-httpclient-4.x

Take a look at this question. It shows how you can set a timeout. From Laz: import org.apache.http.client.HttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; ... // set the connection timeout value to 30 seconds (30000 milliseconds) final HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 30000); client = new DefaultHttpClient(httpParams);...

httpClient post call failing from a servlet with error java.lang.NoSuchMethodError:

java,servlets,post,httpclient,apache-httpclient-4.x

Your code compiled ? And you had this problem at runtime? In which case you have mutiple versions of the library within your classpath. Seeing that the StringEntity class has been inducted from version 4 onwards, it is possible that the server/lib has an earlier version of the library that...

How to specify proxy authentication credentials in Apache httpclient in addition to the target site credentials?

java,authentication,proxy,apache-httpclient-4.x

A CredentialsProvider may manage multiple AuthScopes, see e.g. the implementation in BasicCredentialsProvider (note the call to credMap.put()): @Override public void setCredentials( final AuthScope authscope, final Credentials credentials) { Args.notNull(authscope, "Authentication scope"); credMap.put(authscope, credentials); } So just calling setCredentials() for each scope should work: CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope siteScope...

How to use RestTemplate with Basic Auth

spring,spring-mvc,apache-httpclient-4.x

The astute reader may have noticed that the Authorization header is never sent, and realized the problem. You just have to know that it is a standard protocol to send an unauthorized request, receive a 401 with a WWW-Authenticate header, and make the request again with the Authorization header (I...

Custom protcol interceptor to Apache HttpClient to process exceptions

apache,apache-httpclient-4.x

Protocol interceptors can act on a valid HTTP message only. In case of an I/O error they are useless. You should be using HttpRequestRetryHandler instead

SOAP request using Apache HttpClient

java,web-services,soap,apache-httpclient-4.x

I just executed your code, without modification, and I got back this response: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET"> <GetCitiesByCountryResult> <NewDataSet> <Table> <Country>Brazil</Country> <City>Conceicao Do...

Apache HttpAsyncClient response not received

java,servlets,apache-httpclient-4.x

This is the correct behaviour. You are creating a socket with a conditional Future, and then you proceed to close it without waiting for it. The example code you linked use a "latch" variable to do so. You may move the close code inside future callback, but probably this will...

Server code for handling a file upload made by HttpClient

java,spring,apache-httpclient-4.x,multipartentity

The ultimate answer was that the server method should look like this: @RequestMapping(method = RequestMethod.POST, value = "/upload/") public @ResponseBody String saveUpload(@RequestParam("file") final MultipartFile mpf) throws IOException, ServletException, FileUploadException { File file = new File("C:/dest_path/" + mpf.getOriginalFilename()); FileUtils.writeByteArrayToFile(file, mpf.getBytes()); return "success"; } As mentioned by Sotirios Delimanois the MultipartResolver is...

OAuth2 Authentication in Java using HttpClient

java,curl,oauth-2.0,apache-httpclient-4.x,apache-commons-io

It might be Authorization vs Authentication curl -H "Authorization: Bearer {{access_token}}" VS request.addHeader("Authentication", authorizationString); You might have an easier time using Apache HttpClient, as it is designed for computer to computer communication....

How to refactor the code when the response should always be closed properly?

java,design-patterns,apache-httpclient-4.x

What prevents you from initializing the StopWatch before your wrapper and stopping it in the callback? final Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); new HttpClientWrapper(httpClient).execute(request, new WithResponse<String>() { String withResponse(HttpResponse response) throws Exception { stopwatch.stop(); MDC.put( "backendTime", String.valueOf( stopwatch.elapsed( TimeUnit.MILLISECONDS ) ) ); // ... } }); ...

How to properly clean up after using an HttpClient in a unit test

java,unit-testing,testing,apache-httpclient-4.x

Yes, you should. Shutting down the connection manager (or closing the client with HC 4.3 and newer) is the right thing to do in integration tests.

How to decide optimal settings for setMaxTotal and setDefaultMaxPerRoute?

java,spring,connection-pooling,apache-httpclient-4.x,resttemplate

There are no formula or a recipe that one can apply to all scenarios. Generally with blocking i/o one should have approximately the same max per route setting as the number of worker threads contending for connections. So, having 15 worker threads and 700 connection limit makes little sense to...

Java upload throughput measurements

java,http,upload,apache-httpclient-4.x

getSentBytesCount in HttpConnectionMetrics represents the number of bytes written to the underlying socket / channel. Beyond that JRE can exert no control of how many bytes end up pushed to the network interface.

ConnectionPoolTimeoutException when reaching the max pool size while inserting documents

java,apache-httpclient-4.x,azure-documentdb

You are seeing ConnectionPoolTimeoutException because the DocumentClient does not automatically close the stream when createXXXXXXXX() is called. This behavior was intended to support streaming blob attachments for createAttachment(). To close the stream, you can call close() to close the stream or .getResource() to return the resource and then close the...

NoSuchMethodError when trying to create a WebClient on Glassfish

maven,jersey,apache-httpclient-4.x,htmlunit,jersey-2.0

Apparently moving the HtmlUnit dependency to the bottom of the dependencies list fixed the issue. Like peeskillet mentioned, this isn't a complete fix, as we still don't know what caused the issue in the first place, but it works as a first solution. Please do answer if you find the...

How to load images using HttpClient API

httpclient,apache-httpclient-4.x

I was able to solve this issue. When the client request for the following image, href="/web/common/images/favicon.ico" type="image/x-icon", I am using servlet to read the response from other website.

HttpClient gives Negotiate error with NTLM auth provider

java,authentication,apache-httpclient-4.x,ntlm

I think it is all very simple. Effectively the client is only willing to do NTLM while the server is only willing to do Negotiate, thus failing to agree on a common authentication scheme. This is how one can adjust auth scheme preference to force HttpClient to choose NTLM over...

Getting NoSuchFieldError INSTANCE org/apache/http/message/BasicHeaderValueParser

android,apache-httpclient-4.x,androidhttpclient

Unfortunately stock versions of HttpCore cannot be used in Android. Please use Apache HttpClient Android Port which also includes requisite HttpCore classes compile('org.apache.httpcomponents:httpmime:4.3.6') { exclude module: 'httpclient' } compile 'org.apache.httpcomponents:httpclient-android:4.3.5' ...

Is client implementation for HTTP basic and digest authentication the same?

http,apache-httpclient-4.x,http-authentication,http-basic-authentication,http-digest

Yes, you can and you should. HttpClient is capable of employing different auth schemes in the course of a single request execution (for instance using Basic to authenticate with the proxy and NTLM to authenticate with the origin server)

unit test apache http client proxy 407

apache,junit4,apache-httpclient-4.x,http-proxy

I have done it using the following impl. private CloseableHttpClient httpClient; public HttpClientStub() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { // Trust all certs SSLContext sslcontext = buildSSLContext(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpHost proxy = new HttpHost("someproxy", 8080, "http");...

Streaming an upload with HttpClient/MultipartEntity

java,servlets,proxy,tomcat7,apache-httpclient-4.x

The issue lies in the way your request is processed by the Mime/Multiplart framework (the one you use to process your HTTPServletRequest, and access file parts). The nature of a MIME/Multipart request is simple (at a high level), instead of having a traditionnal key=value content, those requests have much more...

How to write a Serializable as the body of an http post request?

java,http-post,apache-httpclient-4.x

You need to use a BasicHttpEntityEnclosingRequest that contains a SerializableEntity. Basically, it would look something like this: BasicHttpEntityEnclosingRequest postRequest = new BasicHttpEntityEnclosingRequest("POST", "uri"); postRequest.setEntity(new SerializableEntity(yourObject, false)); ...

2 way SSL authentication not working using Apache httpclient: JAVA

java,apache,ssl,https,apache-httpclient-4.x

By default HttpClient does not take system properties into account Try replacing CloseableHttpClient httpclient = HttpClients.createDefault(); with CloseableHttpClient httpclient = HttpClients.createSystem(); ...

Ignoring bad certificate on HTTPS connection when using Apache Async HttpClient 4.0.x

java,apache,ssl,asynchronous,apache-httpclient-4.x

Actually the code that I provided in my question worked. The problem was that I was using Unirest (which uses Apache HttpClient under the hood) and had configured it like this: Unirest.setAsyncHttpClient(createHttpAsyncClient(CONNECTION_TIMEOUT, SOCKET_TIMEOUT)); Unirest.setTimeouts(CONNECTION_TIMEOUT, SOCKET_TIMEOUT); The problem was that "setTimeouts" overrode the configuration I made in createHttpAsyncClient without any indication....

node.js server limiting new connections

javascript,java,node.js,tcp,apache-httpclient-4.x

Since node js v0.12 the http.globalAgent.maxSockets has been set to Infinity, so it is a client side problem. This should set the limit for the client side: http.globalAgent.maxSockets = 1000; Another option is to pass an Agent object to the http request. Have a look at this other question: How...

Unable to run a simple HTTP client in java

java,apache-httpclient-4.x

Basically you get ClassNotFoundException when you dont have corresponding classes at runtime. Here you are missing apache's logging and codec jar on which apache-httpclient depends upon. see dependencies that you need. So once you download them, add them to your classpath or in your -cp command line along with httpcore...

Apache HttpClient not receiving entire response

java,http,apache-httpclient-4.x,chunked-encoding

To gather all the essence of the comments. There is nothing wrong with your code here - using EntityUtils is the recomended way to deal with all kinds of responses. You have error in code that stores your response to the file.

What Java properties to pass to a Java app to authenticate with a http proxy

java,apache-httpclient-4.x,bamboo,http-proxy,apache-httpcomponents

Finally I figured out by trial and error. Passing java.net.useSystemProxies=true along with https.proxyPort, https.proxyHost resolved this. Basically the java vm command line got -Djava.net.useSystemProxies=true -Dhttps.proxyPort=80 -Dhttps.proxyHost=proxyserver.mycompany.com I didn't have to pass https.proxyUser, https.proxyPassword. I believe proxy authentication used the same credentials as my login NTLM credentials....

Solr adding document cycle & wait on response issue

java,solr,apache-httpclient-4.x

Solr can take as many docs, without committing, as you have space in your memory allocated to process (minus regular Solr mem usage). You might have more when doing this in cloud mode. If you want to want to push faster, try csv format in batches :)...

How to send Header using HTTP in JAVA

java,apache-httpclient-4.x

Based on your curl example, this should be your Authorization header: httppost.addHeader("Authorization", "key=AIza*********YUI"); This should resolve your issue. I just confirmed this header with the referenced documentation....

Httpclient 4.3.6: Invalid redirect URI

java,apache-httpclient-4.x

The problem is that braces { and } needs to be encoded in order to form a valid URL: { = %7B } = %7D Full list on URI encoding is available here...

Peer not authenticated in java

java,apache-httpclient-4.x

Technically, seeing as you are using Apache HttpClient 4.x, a simpler solution would be the following: SSLContext sslcontext = null; try { SSLContextBuilder sslContextBuilder = SSLContexts.custom() .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslcontext = sslContextBuilder.build(); Where trustStore is initialized like this KeyStore keyStore = null; try { keyStore = KeyStore.getInstance("BKS", BouncyCastleProvider.PROVIDER_NAME); //you can...

java.lang.NoSuchMethodError org.apache.http.client.utils.URLEncodedUtils.encPath

java,android,apache-httpclient-4.x

Android include outdated Apache HttpClient implementation in their SDK which make it conflict if you add newer Apache Http Client You should use the HttpClient for Android instead Google Android 1.0 was released with a pre-BETA snapshot of Apache HttpClient. To coincide with the first Android release Apache HttpClient 4.0...

How to use SSL with Jersey 2.x and Apache Connection manager

apache-httpclient-4.x,jersey-2.0,jersey-client

Use SSL socket factory configured with system properties Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSystemSocketFactory()) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); ...

Can I skip implementing HttpEntity#getContent()?

java,apache-httpclient-4.x

If entity content cannot be represented as an InputStream getContent method can throw UnsupportedOperationException. Internally HttpClient uses writeTo to stream out entity content to the underlying HTTP connection.

Switching from custom Spring's CommonsHttpInvokerRequestExecutor to HttpComponentsHttpInvokerRequestExecutor

java,spring,authentication,apache-httpclient-4.x,apache-commons-httpclient

So, after discussing the problem from a more global point of view (How to update the settings of an HttpClient in httpclient 4.3+?), here is what I came up with (not totally finished, but the missing interceptor should not be that hard to implement, thanks to Preemptive Basic authentication with...