gpt4 book ai didi

java - 如何将简单的 Curl 调用转换为 Java HttpURLConnection

转载 作者:行者123 更新时间:2023-12-02 10:38:36 24 4
gpt4 key购买 nike

有效的简单curl调用是:curl https://api.github.com/search/repositories\?q\=reactive

我现在在 Java 中尝试的内容

                URL url = new URL("https://api.github.com/search/repositories\\?q\\=reactive");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);

int isError = con.getResponseCode();
System.out.println("Error code is " + isError);

InputStream error = con.getErrorStream();

System.out.println("Error is " + error.toString() + " \n");

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
System.out.println("Error: " + content.toString());

错误代码:404

错误消息:错误:{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}

为什么我这样搜索却找不到呢?

谢谢!

最佳答案

您在java代码中使用的URL与用于curl的转义字符错误。删除转义字符并使用 url https://api.github.com/search/repositories?q=reactive:

public static void main(String[] args) throws IOException {
URL url = new URL("https://api.github.com/search/repositories?q=reactive");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);

System.out.println(con.getResponseMessage());
}

输出:

OK

关于java - 如何将简单的 Curl 调用转换为 Java HttpURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53094736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com