2013-09-05 4 views
7

을 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 

는이 같은 될 subesquest HTTP 요청 될 걸 확인하시기 바랍니다 수 CURL 요청 다음?

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 

위의 컬 요청을 완전히 httpreq로 변환 할 수있는 사람이면 누구든지 친절하게 대응할 수 있습니까?

미리 감사드립니다.

Suvi

답변

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가 더 좋은 선택이라고 생각한다. 당신은 사용자 이름/암호하는 HTTP 헤더 옵션을 설정하는

및 SSL 인증서 유효성 검사를 무시 :

그냥 경우에 당신이 HttpURLConnection를 사용해야합니다, 당신은이 링크를 시도 할 수 있습니다.

HTH

-1

아래는 나를 위해 일한 :

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

------- 
public MyAuthenticator(String user, String passwd){ 
    username=user; 
    password=passwd; 
} 
관련 문제