【问题标题】:Converting CURL request to HTTP Request Java将 CURL 请求转换为 HTTP 请求 Java
【发布时间】:2013-09-05 12:38:41
【问题描述】:

我有以下 CURL 请求 谁能确认一下子请求 HTTP 请求是什么

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

会是这样的吗?

    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

谁能帮我把上面的 curl 请求完全转换成 httpreq。

提前致谢。

苏维

【问题讨论】:

    标签: java curl


    【解决方案1】:

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

    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
    
        }
    }
    

    【讨论】:

    • 您可以从这里为 org.apache.commons.codec.binary.Base64 添加 maven 依赖项: commons-codeccommons-codec1.9
    【解决方案2】:

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

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

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

    HTH

    【讨论】:

      【解决方案3】:

      以下对我有用:

      Authenticator.setDefault(new MyAuthenticator("user@account","password"));
      
      -------
      public MyAuthenticator(String user, String passwd){
          username=user;
          password=passwd;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-06-25
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 2018-04-16
        相关资源
        最近更新 更多