java - 在 Minecraft Mod 中发送 HTTP 请求
问题描述
我正在开发一个 Fabric Minecraft mod,它将发送 http 请求。
这是我使用的代码:
import com.google.gson.JsonObject;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class NetworkUtils {
public static void post(String url, JsonObject json) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
httpClient.close();
}
}
当我在开发环境中运行它时,它运行良好。但是,当我将其构建为 jar 文件并将其放入mods
实际服务器的文件夹中时,会产生以下错误:
java.lang.NoClassDefFoundError: org/apache/http/HttpEntity
我该如何解决?非常感谢你,如果你能帮忙
解决方案
此问题包含有关您收到此错误的原因的多个信息。
当您在开发环境中时,运行它的是您的 IDE。因此,它还将运行所有依赖项。
构建 jar 时,不会导出依赖项。
为此,您可以:
<dependency>
<groupId>my.lib</groupId>
<artifactId>LibName</artifactId>
<version>1.0.0</version>
<scope>compile</scope> <!-- here you have to set compile -->
</dependency>
也有这部分:
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>...</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
configurations {
// configuration that holds jars to include in the jar
extraLibs
}
dependencies {
extraLibs 'my.lib:LibName:1.0.0'
}
jar {
from {
configurations.extraLibs.collect { it.isDirectory() ? it : zipTree(it) }
}
}
- 您可以从自己的外部 jar 加载,如下所述:
File file = new File("mylib.jar");
URL url = file.toURI().toURL();
URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
- 如果您不使用其中之一,则取决于。有时您在导出 jar 时可以直接选择。
推荐阅读
- postgresql - 将多行的 tsvector 合并为一个
- java - Java:wait() 不释放锁。为什么?
- excel - 空 HTML div 上的 VBA 触发事件
- node.js - 警告,FIREBASE_CONFIG 环境变量丢失。初始化 firebase-admin 将失败
- java - 编写一个使用整数密钥加密 .txt 文件的 Java 程序
- python - 如何对 Python ASYNCIO 代码进行分析/基准测试?
- python - pyramid_mailer `Message` 和 `Content-Transfer-Encoding`
- javascript - 在谷歌表格中的同一功能中添加多个范围
- javascript - 列表错误显示在控制台中,但只有一个错误显示在 div
- vba - 将样式应用于选定文本未选定框