JSON RPC Java dzhuvinov-如何设置用户名和密码?
我正在使用来自的JSON-RPC2.0 Java库。我在设置呼叫的用户名和密码时遇到问题。我的代码如下所示:JSON RPC Java dzhuvinov-如何设置用户名和密码?,java,json,http,rpc,basic-authentication,Java,Json,Http,Rpc,Basic Authentication,我正在使用来自的JSON-RPC2.0 Java库。我在设置呼叫的用户名和密码时遇到问题。我的代码如下所示: public static void main(String[] args) { URL serverURL = null; try { serverURL = new URL("http://user:pass@127.0.0.1:18332/"); } catch (MalformedURLException e) { Sys
public static void main(String[] args)
{
URL serverURL = null;
try {
serverURL = new URL("http://user:pass@127.0.0.1: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:pass@127.0.0.1:18332/
在Python中尝试类似的代码,我得到了正确的结果:
access = jsonrpc.ServiceProxy("http://user:pass@127.0.0.1:18332/")
print access.getinfo()
如何为JSON RPC调用配置基本访问身份验证?不确定“dzhuvinov”中的库如何处理流。但您可以应用此代码在
URL
class打开的HTTP传输级别上执行基本身份验证
final String rpcuser ="...";
final String rpcpassword ="...";
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());
}});
URL url = new URL("http://user:pass@127.0.0.1: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);
完整的代码可以在这里找到。我使用它来执行JSON-RPC,以便与Trac
的API通信