4

Old programmer, new to Java. I am trying to run what I think is pretty common example code that is similar in a number of places on the web, HttpClient httpClient = HttpClientBuilder.create().build() throws an exception and I can't figure out why. I'm using HttpClient 4.3.

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class ATest{

   public static void main(String[] args) throws Exception {
      String strURL  = "http://192.9.10.11/cgi-bin/echo";
      String message = "hello world";
      // next line throwsClassNotFoundException, why?
      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpPost   httpPost   = new  HttpPost(strURL);
      httpPost.setEntity(new StringEntity(message));
      HttpResponse response = httpClient.execute(httpPost);
      try {
         System.out.println(response.getStatusLine());
         HttpEntity entity = response.getEntity();
         // do something useful with the response body
         // and ensure it is fully consumed
         EntityUtils.consume(entity);
      } finally {
         response.close();
      }
   }
}
1
  • 2
    A ClassNotFoundException occurs when your application classpath does not contain the specified class. How are you running your application? Commented Oct 4, 2013 at 17:54

2 Answers 2

6

The Java VM comes with a lot of classes but not org.apache.http.*.

You have to help the Java VM, like you help gcc to link a binary in C or C++ with -lxxx and LD_LIBRARY_PATH, with the classpath notion. java -cp <path>:<path>:<path> specify where are the classes needed (like the .so for binaries under Unix).

org.apache.http.* classes are located into a jar. you have to specify this jar path into cp <path> spec.

The jars contained in the apache http client 4.3 delivery are located in the lib directory:

  • httpclient-4.3.jar
  • httpmime-4.3.jar
  • fluent-hc-4.3.jar
  • httpclient-cache-4.3.jar
  • httpcore-4.3.jar
  • commons-logging-1.1.3.jar
  • commons-codec-1.6.jar

You don't need all if your code is just a sample, I suggest commons-logging-1.1.3.jar and httpclient-4.3.jar

Sign up to request clarification or add additional context in comments.

1 Comment

I see, i needed more (all) of the apache jars from the zip file. Duh, thanks.
0

Try including the below dependency in your build.gradle app module

compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.