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

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



我非常感谢获得帮助。

最佳答案

鉴于您正在使用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的sample for 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返回自定义对象类型。

08-28 00:42