首页 > 解决方案 > 在 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

我该如何解决?非常感谢你,如果你能帮忙

标签: javahttpminecraftminecraft-fabric

解决方案


问题包含有关您收到此错误的原因的多个信息。

当您在开发环境中时,运行它的是您的 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 时可以直接选择。

推荐阅读