2013-09-05 74 views
7

Tôi có sau đây yêu cầu CURL bất cứ ai có thể vui lòng xác nhận cho tôi những gì sẽ là yêu cầu HTTP subesquestChuyển đổi yêu cầu CURL HTTP Request Java

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

Nó sẽ là một cái gì đó như thế nào?

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 

Bất kỳ ai cũng có thể giúp tôi chuyển đổi yêu cầu curl ở trên hoàn toàn thành httpreq.

Xin cảm ơn trước.

Suvi

Trả lời

12

Có rất nhiều cách để đạt được điều này. Dưới đây là một trong những đơn giản nhất trong quan điểm của tôi, Đồng ý nó không phải là rất linh hoạt nhưng hoạt động.

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

Bạn có thể thêm phụ thuộc maven cho org.apache.commons.codec.binary.Base64 từ đây: <- https: // mvnrepository .com/vật/commons-codec/commons-codec -> commons-codec commons-codec 1,9 kishorer747

2

Tôi không chắc liệu HttpURLConnection là người bạn tốt nhất của bạn ở đây chưa. Tôi nghĩ rằng Apache HttpClient là một lựa chọn tốt hơn ở đây.

Chỉ trong trường hợp bạn phải sử dụng HttpURLConnection, bạn có thể thử liên kết này:

Bạn đang thiết tên người dùng/mật khẩu, một lựa chọn HTTP Header và bỏ qua SSL xác nhận chứng chỉ.

HTH

-1

Dưới đây từng làm việc cho tôi:

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

------- 
public MyAuthenticator(String user, String passwd){ 
    username=user; 
    password=passwd; 
} 
Các vấn đề liên quan