2013-09-05 220 views
7

我有以下的卷曲请求任何人都可以跟我确认这将是subesquest HTTP请求转换CURL请求HTTP请求的Java

 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。

在此先感谢。

苏维

回答

12

有许多方法来实现这一目标。下面的一个最简单,我认为,同意它不是很灵活,但工作。

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 

    } 
} 
+0

你可以在这里添加行家依赖于org.apache.commons.codec.binary.Base64: < - HTTPS:// mvnrepository的.com /伪影/公地编解码器/公地编解码器 - > 公地编解码器 公地编解码器 1.9 kishorer747

2

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

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

要设置用户名/密码,一个HTTP标头的选项,而忽略SSL证书验证。

HTH

-1

下面为我工作:

Authenticator.setDefault(new MyAuthenticator("[email protected]","password")); 

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