Category Archives: apache-commons-httpclient

Apache HTTP Client 3 does not use pre-emptive authentication on some URL’s

I have two REST URL's. One is /accessmanager/sessions POST and the other one is /accessmanager/sessions/{token} POST.

The code goes through the following method, ONLY the URL is different.

private String doLogin(final String username, final String password, final String path,
        final int... expectedSatusCodes) throws AcmaException {

    // Setup credentials
    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);

    String userCredentials = username + ":" + password;     

    // Setup HTTP client, prepare for login
    HttpClient client = this.getClient();

    client.getState().setCredentials(AuthScope.ANY, defaultcreds);

    // Setup POST method
    PostMethod method = new PostMethod(path);

    try {
        RequestEntity body = new StringRequestEntity("none", (String) null, (String) null);

        ObjectMapper mapper = new ObjectMapper();
        AccessManagerRESTImpl.LOG.debug("RETURNED === " + mapper.writeValueAsString(body));
    } catch (UnsupportedEncodingException ex) {
        throw new AcmaException(ex);
    } catch (JsonProcessingException e) {

    Header locationHeader = null;
    try {
        this.executeMethod(client, method);

        AccessManagerRESTImpl.LOG.debug("Response " + method.getStatusLine().toString());

        this.checkStatusCode(method, expectedSatusCodes);

        locationHeader = method.getResponseHeader(AccessManagerRESTImpl.HTTP_HEADER_LOCATION);
    } finally {


    return returnedToken;

Now, the first URL always works with Basic Auth. But the second one always return 400 Bad Request: Missing Authorization header.

I have checked that the credentials are OK and added to the Client's state. All is fine. So I am clutching at straws why this second call always fails. I know about pre-emptive authentication so I tried with

method.setRequestHeader("Authorization", basicAuth);

And then it works. Problem is, I am not allowed to upgrade the client, so I can't move to HttpClient 4 and I can't add this "Authorization" header.

But still, why does the first URL always work and why does the second with the {token} never work? As this is the same httpclient code:

private HttpClient getClient() throws AcmaException {

    if (this.httpclient == null) {
        this.httpclient = new HttpClient(this.connectionManager);

        this.httpclient.getHostConfiguration().setHost(this.otasUri.getHost(), this.otasUri.getPort(),

        int timeOut = AccessManagerRESTImpl.HTTP_CLIENT_TIMEOUT;
        if (timeOut > 0) {
            HttpConnectionParams params = this.httpclient.getHttpConnectionManager().getParams();

    return this.httpclient;

The Rest API of both URL's contains the Basic Auth path param, so on server side it is all OK. Also tried the second URL with Curl. That also works fine.

Any hint/tip is greatly appreciated!


So I found out that the URL with the {param} never uses pre-emptive AUTH. But the one without param, just plain /accessmanager/sessions does use pre-emptive.

Can anybody explain this?

HCP JEE6 Application with Destination fails when server does not support TLS 1.0

We are consuming RESTful services external to a Hana Cloud Platform Java application. We are able to interact with these destinations setup in HCP via the Apache HttpClient (v4.1.3) provided as part of the application JEE6 profile and other HCP libraries, the application is configured to use JRE 7.

The integration infrastructure vendor we are connecting to, disabled TLSv1.0 recently and since then we are getting errors when trying to connect to the REST services.

This is the stacktrace: peer not authenticated
at org.apache.http.conn.ssl.AbstractVerifier.verify(
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(
at org.apache.http.impl.client.DefaultRequestDirector.execute(
at org.apache.http.impl.client.AbstractHttpClient.execute(
at my.domain.hcp.HttpRequestSupport.service(
at javax.servlet.http.HttpServlet.service(
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
at org.apache.catalina.core.ApplicationFilterChain.doFilter(
at org.apache.tomcat.websocket.server.WsFilter.doFilter(
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
at org.apache.catalina.core.ApplicationFilterChain.doFilter(
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
at org.apache.catalina.core.ApplicationFilterChain.doFilter(
at org.apache.catalina.core.StandardWrapperValve.invoke(
at org.apache.catalina.core.StandardContextValve.invoke(
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(
at org.apache.catalina.core.StandardHostValve.invoke(
at org.apache.catalina.valves.AccessLogValve.invoke(
at org.apache.catalina.valves.ErrorReportValve.invoke(
at org.apache.catalina.core.StandardEngineValve.invoke(
at org.apache.catalina.connector.CoyoteAdapter.service(
at org.apache.coyote.http11.AbstractHttp11Processor.process(
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
at java.util.concurrent.ThreadPoolExecutor.runWorker(
at java.util.concurrent.ThreadPoolExecutor$
at org.apache.tomcat.util.threads.TaskThread$

We have tried adding the JVM arguments to the Java application to force it to use TLSv1.1 or TLSv1.2 and not use TLSv1.0:


Setting the JVM argument does nothing, it seems like the Apache HttpClient library ignores this setting. Is there another way to force the Apache HttpClient (v4.1.3) to a newer version of TLS?

Ajax js call , Httpclient java impact on server

We have a server which will handle servlet call and fetch the data. So we have two different type of clients

  1. Java script client ,through ajax calls we make servlet call.
  2. Http-Client java to make servlet call using NIO.

Note : Both are GET calls only.

Does these two different ways of calling servlet have any difference. Will there be any difference of resources on server handling these different mediums....

400 – Bad Request on Apache POST sending JSON

I'm trying to make a REST call from my class using the Apache. But its giving the 400 exception when I print the response of the REST service. Kindly find the code below and let me know the changes that needs to be made to make it working,

    List<NameValuePair> pickup = new ArrayList<NameValuePair>();
    ArrayList<HashMap> pickupItemList = new ArrayList<HashMap>();

    String [] productIds = prop.getArray("vproductIDs");
    String [] quantities = prop.getArray("vquantities");
    String [] tprices = prop.getArray("vtprices");
    String [] bprices = prop.getArray("vbprices");

    HashMap pickupObjMap = new HashMap<String, Object>();

    for(int i=0; i<productIds.length ; i++){
        HashMap map = new HashMap<String, Object>();
        map.put("sku", productIds[i]);
        map.put("quantity", Double.parseDouble(quantities[i]));
        map.put("totalPrice", Double.parseDouble(tprices[i]));
        map.put("basePrice", Double.parseDouble(bprices[i]));
    pickup.add(new BasicNameValuePair("pickupItemList", pickupItemList.toString()));
    pickup.add(new BasicNameValuePair("pickupObj", pickupObjMap.toString()));
    pickup.add(new BasicNameValuePair("ovclid", prop.getString("ovclid")));

        HttpPost httppost = new HttpPost("Target URL");
        try {
            httppost.setEntity(new UrlEncodedFormEntity(pickup));
            httppost.setHeader("Content-Type", "application/json");
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            if (bufferedReader != null) {
                int cp;
                StringBuilder sb = new StringBuilder();
                while ((cp = != -1) {
                    sb.append((char) cp);
                System.out.println("String Response......."+sb);
        } catch (Exception e) {


Below is the response that I get upon making the REST Call.

Unexpected character ('p' (code 112)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') 
at [Source: [email protected]; line: 1, column: 2]

NoClassDefFoundError when runnung on server using apache commons httpclient lib

i'm writing a dynamic-web-project with wildfly as my web-server by java
in this project, i want to connect with other server
the library i'm using is apache.commons
however, the function works when i run as application
but once i run as server, it comes out an exception, NoClassDefFoundError, pointing at the line i new the object
( ConnectUtil util = new ConnectUtil() ) <- line of error triggered
i have tried to import the .jar below but still not working

  • comments-codec-1.10
  • comments-fileupload-1.3.1
  • comments-httpclient-3.1
  • comments-io-2.4
  • comments-lang-2.6
  • comments-logging-1.2
  • comments-ssl
  • how can i solve this?

    here's some code in

    public Response openUrl(String host, String url, int port, 
        HashMap<String, String> params, int timeout) {
    Response result = new Response();
        // init PostMethod object.
    Protocol mHttps = new Protocol("https", new EasySSLProtocolSocketFactory(), port);
    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(host, port, mHttps);
    byte[] response = null;
    PostMethod method = new PostMethod(url);
    try {
        int code = client.executeMethod(method);
    } catch (Exception e) {
    } finally {
        if (method != null)
    return result;


    and the stack trace is:

    ERROR [io.indertow.request] (default-55) UT005023: Exception handling request to /MyWebServicePath: java.lang.NoClassDefFoundError: org/apache/commons/httpclient/protocal/SecureProtocalSocketFactory

    error happens when ConnectUtil util = new ConnectUtil()


    org.apache.commons.httpclient.HttpClient multithreading calls crash

    Hi all I use apache's httpclient to make restcalls, everything is working fine, When multiple thread are using this method my app crashes. What is the implementation for this class that is MultithreadSafe.

    Here is my code.

            httpClient = new HttpClient();
            HttpMethod method = null;
            method = new GetMethod();
               ... method creation...

    Thanks in advance. Juan

    http client 3.0.1 sometimes stuck while reading response

    we use apache httpclient 3.0.1 in prod. environment. It generally works OK but sometimes it can not read response from the server. And unfortunately thread is get stucked for hours.

    And in the log the following lines appear for hours unless restart the application:

    2014-12-15 18:29:58,328 DEBUG enter HttpParser.readLine(InputStream, String)
    2014-12-15 18:29:58,328 DEBUG enter HttpParser.readRawLine()
    2014-12-15 18:29:58,328 DEBUG  enter HttpConnection.readLine()

    Note: All the timeout properties are set to reasonable values.

    HttpGetType result = new HttpGetType();
            HttpClient client = new HttpClient(connectionManager);
            PostMethod method = new PostMethod(url);
            if (proxy) {
                HostConfiguration config = new HostConfiguration();
                config.setProxy(PROXY_IP, PROXY_PORT);
  "post url:" + url);
  "sent post:" + body);
            try {
                method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
                // method.setRequestEntity(new StringRequestEntity(body, "text/plain","UTF-8"));
                method.setRequestEntity(new StringRequestEntity(body));
                if (method.getStatusCode() == HttpStatus.SC_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                    String line = null;
                    StringBuffer respBuf = new StringBuffer();
                    while ((line = br.readLine()) != null) {
                    result.setParams(true, respBuf.toString());
          "received post:" + result.getMessage());
                } else {
                    logger.warn("httppost return code:" + method.getStatusCode());
            } catch (Exception e) {
            } finally {
                if (method != null)

    When should the HttpClient be closed?

    I am building an Android app that will fire multiple HTTP requests (say a request every second) to a server to fetch data. What are the best practices I must follow?

    Should I create and close the client after each request, like the following?

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {
        HttpPost request = new HttpPost("http://yoururl");
        StringEntity params = new StringEntity(json.toString());
        request.addHeader("content-type", "application/json");
    // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {

    Or should I create a client initially, use it for all requests and then finally close it when I'm done with it?

    Apache httpClient error on Android

    I have a desktop Java application to upload an image to server using Apache Commons httpClient lib (v4.3.6) and I am trying to replicate the solution in Android.

    The issue is that I get different response on executing the below statement on Java (which is correct) and Android (incorrect)

    HttpResponse response = client.execute(post);

    I referred to the post at HttpClient from apache in Android? which provides some information, but did not help me.

    I also tried to use the "Android port httpClient jar files" v4.3.3 and v.4.3.5 from but was unsuccessful, as I got NoClassDefFoundError exception on executing

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    I have currently switched back to using default java build jar files for HttpClient on Android.

    Below is my current code in Android (java is exactly same except the imageFilePath). Any pointers or help is greatly appreciated!

      HttpClient client = new DefaultHttpClient();
      String url="";
      String imageFilePath = Environment.getExternalStorageDirectory().getPath() +"/test.jpg"; 
      HttpPost post = new HttpPost(url);
      String boundary = "-------------" + System.currentTimeMillis();
      post.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
      MultipartEntityBuilder entityB = MultipartEntityBuilder.create();
      entityB.addPart("bih",new StringBody("200"));
      entityB.addPart("biw",new StringBody("160"));
      entityB.addPart("encoded_image", new FileBody(new File(imageFilePath)));  // Code snippet A
     //  Code snippet B - I am not sure if snippet A or snippet B is correct to add an encoded image
     // if(file != null)
     //    {
     //        entityB.addBinaryBody("encoded_image", file);
     //    }
      entityB.addPart("image_url",new StringBody(""));
      entityB.addPart("image_content",new StringBody(""));
      entityB.addPart("filename",new StringBody(""));
      entityB.addPart("h1",new StringBody("en"));
      HttpEntity entity =;
     HttpResponse response = client.execute(post);

    httpClient POST and multipart and encoding

    I have a Java Applet which uses httpclient to POST multipart files to a Servlet, the Applet for some unknow reason for me, POST ISO-8859-1 to the server side (Servlet), on server side I must handle UTF-8. I'm sending a file e.g. ├ęclave and on server side I'm getting ?clave.

    Here's my code Applet side:

            PostMethod post = new PostMethod(urlDest + "&jsessionid="+ sessionId);
            Part[] parts = {
                    new StringPart("uploadDir", dirUpload ? "true" : "false"),
                    new StringPart("uploadedBasePath", URLEncoder.encode(path,
                    new StringPart("uploadedFullPath",
                                    .getAbsolutePath(), "UTF-8")),
                    new StringPart("uploadedFileName", URLEncoder.encode(
                            toUpload.getName(), "UTF-8")),
                    new StringPart("uploadedTableName", URLEncoder.encode(
                            tableName, "UTF-8")),
                    new StringPart("uploadedFileModificationDate",
                            URLEncoder.encode(dateString, "UTF-8")), part };
            post.setRequestEntity(new MultipartRequestEntity(parts, post
            if (toUpload.getName().toLowerCase().endsWith(".msg")) {
            if (this.authorization != null) {
                post.addRequestHeader("Authorization", this.authorization);
            HttpClient client = new HttpClient();
            int status = client.executeMethod(post);
            sResult = post.getResponseBodyAsString();
            //sResult = new String(post.getResponseBody(),"UTF-8");
            if (sResult == null || sResult.equals(""))
                sResult = "";

    Just in case, server side extract...

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {"Recieved new Upload request");
        StringBuffer respContent = new StringBuffer("");
        if (ServletFileUpload.isMultipartContent(req)) {
            ServletFileUpload upload = new ServletFileUpload(
                    new DiskFileItemFactory());
            upload.setProgressListener(new UploadProgressListener(req
            // use all lower case tags because of browser compatibility issues
            // (IE)
            try {
                // Parse the request
                FileItemIterator iter = upload.getItemIterator(req);
                while (iter.hasNext()) {
                    FileItemStream item =;
                    String name = item.getFieldName();
                    InputStream stream = item.openStream();
                    if (item.isFormField()) {
              "Form field " + name + " with value "
                                + Streams.asString(stream) + " detected.");
                    } else {
                        FileItemHeaders headers = item.getHeaders();
                        if (headers != null) {
                            Iterator<String> it = headers.getHeaderNames();
                            while (it.hasNext()) {
                                String hname =;
                                System.out.println(hname + "="
                                        + headers.getHeader(hname));
                        FileWrapper f = new FileWrapper();
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        Streams.copy(stream, bout, true);
                        String contentType = "application/octet-stream";
                        if (item.getContentType() != null
                                && item.getContentType().length() > 0) {
                            contentType = item.getContentType();
                        System.out.println("coding file name servlet side:" +  new String (item.getName().getBytes(),"UTF-8"));
                        System.out.println("coding file name servlet side:" +  URLDecoder.decode(item.getName(),"UTF-8"));
                        System.out.println("Testing iso");
                        System.out.println("coding file name servlet side:" +  new String (item.getName().getBytes(),"ISO-8859-1"));
                        System.out.println("coding file name servlet side:" +  URLDecoder.decode(item.getName(),"ISO-8859-1"));
                        Long id =;
                        respContent.append("<contenttype>" + contentType
                                + "</contenttype>");
                        respContent.append("<name>" + f.getFileName()
                                + "</name>");
                        respContent.append("<id>" + id + "</id>");
            } catch (FileUploadIOException fioe) {
                try {
                    throw fioe.getCause();
                } catch (FileSizeLimitExceededException fslee) {
                    System.out.println("fioe == " + fioe);
                    respContent.append("<maxsize>" + fslee.getPermittedSize()
                            / 1024 / 1024 + "</maxsize>");
                    respContent.append("<actualsize>" + fslee.getActualSize()
                            / 1024 / 1024 + "</actualsize>");
                } catch (Throwable t) {
                    throw new RuntimeException(t);
            } catch (Exception ex) {
                throw new RuntimeException(ex);

    Thank you very much, I really apreciate your help...