Search code examples
javajsonhttprpcbasic-authentication

JSON RPC Java dzhuvinov - how to set username and password?


I am using the Java library for JSON-RPC 2.0 from dzhuvinov. I am having problems setting my username and password for basic access authenticaition for the calls. My code looks like:

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());
}

And I get a response of:

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

Trying a similar code in Python I get a proper result:

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

How can I configure the basic access authentication for my JSON RPC calls?


Solution

  • final String rpcuser ="...";
    final String rpcpassword ="...";
    
    Authenticator.setDefault(new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());
      }});