繁体   English   中英

在 Minecraft Mod 中发送 HTTP 请求

[英]Sending HTTP requests in a Minecraft Mod

我正在开发一个 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的时候直接有一个选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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