首页 > 解决方案 > java.lang.ClassNotFoundException: org.apache.http.HttpEntity 在 HttpPost

问题描述

我正在使用 java 8

我正在尝试使用 JSON 正文执行 HTTP POST 请求,然后将响应作为字符串获取,以便能够将其解析为 Gson (JsonObject)

但 !

当我使用HttpEntityor 时BasicResponseHandler,我遇到了这个错误:java.lang.NoClassDefFoundError: org/apache/http/HttpEntity

这是我拥有的 gradle 依赖项 compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.13'

这是我的 Post 请求的代码:

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;
    }

标签: javajava-8httpresponseminecrafthttpentity

解决方案


我修好了它 !

这是解决方案(以及它发生的原因)

为了运行我的程序,我必须将它打包到一个 jar 中,当我打包到一个 jar 中时,不包括依赖项。

然后我不得不编辑我的 build.gradle

首先,我像这样添加了 gradle 插件“应用程序”:

plugins {
    id "java"
    id 'application'
}

然后我在 StackOverflow 上找到了一个代码片段,它下载所有依赖项并将它们包含到 jar 中:链接到帖子

希望它可以帮助有同样问题的人!

快乐的函数编写!


推荐阅读