我正在尝试制作一个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
我非常感谢获得帮助。
最佳答案
鉴于您正在使用 JDK-11(存在非投诉 java.net.http
包),您正在使用的 API 已更改为 BodyPublishers.ofString
和 BodyHandlers.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 孵化器模块期间最初设计的内容,因此您可能会找到有关以前语法的文档。
另外:这是一个sample for POST来自openjdk的请求。
<小时/>此外,正如 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-databind
和 jackson-core
文物。
注意:您可以在更通用的实现中使用 readValue
来返回自定义对象类型。
关于java - 使用 Java 创建 Hastebin Paste,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53569900/