简体   繁体   English

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

[英]How to convert simple Curl call to Java HttpURLConnection

Simple curl call that works is: curl https://api.github.com/search/repositories\\?q\\=reactive 起作用的简单curl调用是: curl https://api.github.com/search/repositories\\?q\\=reactive

What I'm attempting right now in Java 我现在在用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());

Error code: 404 错误代码: 404

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

Why would it not be found when I search it in that manner? 当我以这种方式搜索它时,为什么找不到它?

Thank you! 谢谢!

The URL you are using in java code is wrong with escape characters used for curl. 您在Java代码中使用的URL与用于curl的转义字符是错误的。 Remove the escape characters and use the url https://api.github.com/search/repositories?q=reactive : 删除转义字符并使用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());
}

Output: 输出:

OK

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

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