将 CURL 请求转换为 HTTP 请求 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18636567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:43:59  来源:igfitidea点击:

Converting CURL request to HTTP Request Java

javacurl

提问by user2686807

I have the following CURL request Can anyone please confirm me what would be the subesquest HTTP Request

我有以下 CURL 请求任何人都可以确认我什么是 subesquest HTTP 请求

      curl -u "Login-dummy:password-dummy" -H "X-Requested-With: Curl" "https://qualysapi.qualys.eu/api/2.0/fo/report/?action=list" -k

Will it be something like ?

会是这样吗?

    String url = "https://qualysapi.qualys.eu/api/2.0/fo/report/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET"); ..... //incomplete

Can anyone be kind enough to help me convert the above curl request completely to httpreq.

任何人都可以帮助我将上述 curl 请求完全转换为 httpreq。

Thanks in advance.

提前致谢。

Suvi

苏维

采纳答案by Ashay Thorat

There are numerous ways to achieve this. Below one is simplest in my opinion, Agree it isn't very flexible but works.

有很多方法可以实现这一点。我认为下面是最简单的,同意它不是很灵活但有效。

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.codec.binary.Base64;

public class HttpClient {

    public static void main(String args[]) throws IOException {
        String stringUrl = "https://qualysapi.qualys.eu/api/2.0/fo/report/?action=list";
        URL url = new URL(stringUrl);
        URLConnection uc = url.openConnection();

        uc.setRequestProperty("X-Requested-With", "Curl");

        String userpass = "username" + ":" + "password";
        String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        uc.setRequestProperty("Authorization", basicAuth);

        InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
        // read this input

    }
}

回答by BetaRide

I'm not sure whether HttpURLConnectionis your best friend here. I think Apache HttpClientis a better option here.

我不确定HttpURLConnection你是否是这里最好的朋友。我认为Apache HttpClient是这里更好的选择。

Just in case you must use HttpURLConnection, you can try this links:

以防万一你必须使用HttpURLConnection,你可以试试这个链接:

You are setting username/password, a HTTP-Header option and ignore SSL certificate validation.

您正在设置用户名/密码、HTTP-Header 选项并忽略 SSL 证书验证。

HTH

HTH

回答by ajgeor

Below worked for me:

以下为我工作:

Authenticator.setDefault(new MyAuthenticator("user@account","password"));

-------
public MyAuthenticator(String user, String passwd){
    username=user;
    password=passwd;
}