2013-09-05 22 views
7
にCURLリクエストの変換

私は、次のCURLリクエストは、誰もが、それはのようになりますsubesquest HTTPリクエスト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 

上記のカールリクエストを完全にhttpreqに変換するのに役立つ人はいますか?

ありがとうございます。

Suvi

答えて

12

これを達成するための多数の方法があります。下の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 

    } 
} 
+0

あなたがここからorg.apache.commons.codec.binary.Base64ためのMavenの依存関係を追加することができます < - の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; 
}