简体   繁体   中英

java.lang.ClassNotFoundException: org.apache.http.HttpEntity on HttpPost

I'm working with java 8

I'm trying to do a HTTP POST request with a JSON body and then get the response as a string so I'll be able to parse it as Gson (JsonObject)

But !

When i use the HttpEntity or the BasicResponseHandler , i'm faced with this error : java.lang.NoClassDefFoundError: org/apache/http/HttpEntity

Here's the gradle dependency that i have compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.13'

And here's the code of my Post request :

private static JsonObject execPostRequestTest(URL url, String jsonString) {

        StringEntity stringEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(url.toString());
        request.setEntity(stringEntity);

        try {
            HttpResponse httpResponse = httpClient.execute(request);

            String responseString = new BasicResponseHandler().handleResponse(httpResponse);

            return new JsonParser().parse(responseString).getAsJsonObject();

        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

I fixed it !

Here's the solution (and the reason why it occured)

To run my program, I had to pack it into a jar and when I packed into a jar, dependencies were not included.

Then I had to edit my build.gradle

First, I added the gradle plugins "application" like this :

plugins {
    id "java"
    id 'application'
}

Then I found a code snippet on StackOverflow that downloads all denpendencies and include them into the jar : Link to the post

Hope it can help people that had the same issue !

Happy function writing !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM