2013-02-09 109 views
1

我正在使用來自dzhuvinov的JSON-RPC 2.0的Java庫。我在爲呼叫設置我的用戶名和密碼爲basic access authenticaition時遇到問題。我的代碼如下所示:JSON RPC Java dzhuvinov - 如何設置用戶名和密碼?

public static void main(String[] args) 
{ 
    URL serverURL = null; 
    try { 
     serverURL = new URL("http://user:[email protected]:18332/"); 

    } catch (MalformedURLException e) { 
     System.err.println(e.getMessage()); 
     return; 
    } 
    JSONRPC2Session mySession = new JSONRPC2Session(serverURL); 
    String method = "getinfo"; 
    int requestID = 0; 
    JSONRPC2Request request = new JSONRPC2Request(method, requestID); 
    JSONRPC2Response response = null; 
    try { 
      response = mySession.send(request); 

    } catch (JSONRPC2SessionException e) { 
      System.err.println(e.getMessage()); 
      return; 
    } 
    if (response.indicatesSuccess()) 
     System.out.println(response.getResult()); 
    else 
     System.out.println(response.getError().getMessage()); 
} 

而且我得到的迴應:

Network exception: Server returned HTTP response code: 401 for URL: http://user:[email protected]:18332/ 

嘗試在Python類似的代碼,我得到正確的結果:

access = jsonrpc.ServiceProxy("http://user:[email protected]:18332/") 
print access.getinfo() 

我如何配置我的JSON RPC調用的基本訪問身份驗證?

回答

1
final String rpcuser ="..."; 
final String rpcpassword ="..."; 

Authenticator.setDefault(new Authenticator() { 
    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray()); 
    }}); 
1

不知道如何從庫 'dzhuvinov' 與流的交易。但是您可以應用此代碼在由URL類打開的HTTP傳輸級別上執行基本身份驗證。

URL url = new URL("http://user:[email protected]:18332/"); 
URLConnection conn = url.openConnection(); 
String userpass = rpcuser + ":" + rpcpassword; 
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes())); 
conn.setRequestProperty ("Authorization", basicAuth); 
conn.setRequestProperty ("Content-Type", "application/json"); 
conn.setDoOutput(true); 

完整代碼可以在這裏找到http://engnick.blogspot.ru/2013/03/java-trac-rpc-and-json.html。我用它來執行JSON-RPC的東西來與Trac的API進行通信。

相關問題