I am using HttpClient components from Apache for the following simple program and I see the below exception:
Exception in thread \"main\" java.lang.NoSuchFieldErr
This code works...without any error.. check the packages if you are using similar import .
package com.jai.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpExample {
/**
* @param args
*/
public static void main(String[] args) {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://www.google.com/?q=java");
try {
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I had this problem. It looks like there is a problem while initializing HttpClient with HttpClientBuilder.create().build(). If you want more immediate solution just use new DefaultHttpClient() to initialize HttpClient.
HttpClient client = new DefaultHttpClient();
I also was frustrated by this and Eclipse until I realized that similar to Pat B's Webpshere tip, it does cause issues for Eclipse if you have the dependencies in the wrong order.
Properties -> Java Build Path -> Order and Export
Play a bit around here with the order of core and client.
I had this problem with Hadoop. It used an old version of httpclient-4.2.5.jar
and httpcore-4.2.5.jar
in their shared lib.
I solved this by shading parts via the maven-shade-plugin
<relocations>
<relocation>
<pattern>org.apache.http</pattern>
<shadedPattern>shaded.org.apache.http</shadedPattern>
</relocation>
</relocations>
Caused by: java.lang.NoSuchFieldError: INSTANCE
one of the solution of java.lang.NoSuchFieldError: INSTANCE : This happens if we have two diff version of same class in our classpath…. […], So we first find that class(one version of class) , click that class, select "build path", then we click "remove from build path" . by 333ccc333
For those using Webpshere, make sure your class loading policy is set to "Parent Last", otherwise it will not work since WAS is using its own version of commons http which can be conflicting.