0

我正在尝试制作一个 java 程序,我可以给她一个字符串,它将它粘贴到 Hastebin(www.hastebin.com) 并将粘贴的 URL 打印到控制台,这是我拥有的代码: Main.java(主类):

public class Main {
    Hastebin hastebin;
    static String randomString = "HELLO";

    public static void main(String args[]) {
        System.out.println(Hastebin.paste((randomString)));
    }
}

我的 Hastebin.java 类:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Hastebin {

public static String paste(String content){
    final HttpClient client = HttpClient.newHttpClient();
    final HttpRequest request = HttpRequest.newBuilder(
            URI.create("https://hastebin.com/documents")
    ).POST(HttpRequest.BodyPublisher.fromString(content).build());

    final HttpResponse<String> response = client.send(request, 
    HttpResponse.BodyHandler.asString());
    final String responseContent = response.body();
    final JSONObject responseJson = new JSONObject(responseContent);
    final String key = responseJson.getString("key");
    return "https://hastebin.com/" + key;
    }
}

我的错误:

Error:(14, 48) java: cannot find symbol
symbol:   method fromString(java.lang.String)
location: interface java.net.http.HttpRequest.BodyPublisher

Error:(17, 92) java: cannot find symbol
symbol:   method asString()
location: interface java.net.http.HttpResponse.BodyHandler

Error:(19, 15) java: cannot find symbol
symbol:   class JSONObject
location: class Hastebin

Error:(19, 45) java: cannot find symbol
symbol:   class JSONObject
location: class Hastebin

我真的很感激能得到帮助。

4

1 回答 1

1

鉴于您正在使用 JDK-11(存在非抱怨java.net.http包),您正在使用的 API 已更改为BodyPublishers.ofStringBodyHandlers.ofString. 您可以在代码中将它们更新为:

final HttpRequest request = HttpRequest.newBuilder(URI.create("https://hastebin.com/documents"))
            .POST(HttpRequest.BodyPublishers.ofString(content)).build();

final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

注意:API 已更改为在 Java9 的孵化器模块期间最初设计的内容,因此您可能会找到有关先前语法的文档。

另外:这是来自 openjdk的 POST 请求的示例。


此外,如GET JSON示例中所述,如果您想将响应作为自定义对象读取,您可以使用自定义对象映射器:

class UncheckedObjectMapper extends com.fasterxml.jackson.databind.ObjectMapper {
    Map<String, String> readValue(String content) {
        try {
            return this.readValue(content, new com.fasterxml.jackson.core.type.TypeReference() {
            });
        } catch (IOException ioe) {
            throw new CompletionException(ioe);
        }
    }
}

然后将您的回复阅读为

final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, String> mappedResponse = new UncheckedObjectMapper().readValue(response.body());

要解析上述完全限定的类名,您将需要依赖项jackson-databindjackson-core工件。

注意:您可以使用readValue更通用的实现来返回自定义对象类型。

于 2018-12-01T10:36:53.483 回答