![](/img/trans.png)
[英]java.lang.ClassNotFoundException: org.apache.http.config.RegistryBuilder
[英]java.lang.ClassNotFoundException: org.apache.http.HttpEntity on HttpPost
我正在使用 Java 8
我正在嘗試使用 JSON 主體執行 HTTP POST 請求,然后將響應作為字符串獲取,以便我能夠將其解析為 Gson (JsonObject)
但 !
當我使用HttpEntity
或BasicResponseHandler
,我遇到了這個錯誤: java.lang.NoClassDefFoundError: org/apache/http/HttpEntity
這是我compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.13'
的 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;
}
我修好了它 !
這是解決方案(以及它發生的原因)
為了運行我的程序,我必須將它打包到一個 jar 中,當我打包到一個 jar 中時,不包含依賴項。
然后我不得不編輯我的 build.gradle
首先,我像這樣添加了 gradle 插件“應用程序”:
plugins {
id "java"
id 'application'
}
然后我在 StackOverflow 上找到了一個代碼片段,它下載所有的依賴項並將它們包含到 jar 中: 鏈接到帖子
希望能幫到遇到同樣問題的人!
快樂的函數寫作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.