我在尝试访问api时遇到401错误,api需要我提供的用户名和密码。我使用jsonrpc2库来完成这一切。这是我的代码:
App.java
public class App {
public static JSONRPC2Session rpcSession;
private static final String MONERO_URL = "http://localhost:18082/json_rpc";
public static int requestId = 1;
public static JSONRPC2Request request;
public static JSONRPC2Response response;
public static void main(String[] args) throws MalformedURLException, JSONRPC2SessionException
{
MoneroClient client = new MoneroClient(MONERO_URL);
client.getBalance();
}
}
MoneroClient.java
public class MoneroClient {
private int requestId = 0;
private JSONRPC2Session rpcSession;
public MoneroClient(String url) throws MalformedURLException {
rpcSession = new JSONRPC2Session(new URL(url));
rpcSession.setRawResponseInspector(new MyInspector());
rpcSession.setConnectionConfigurator(new BasicAuthenticator());
}
public BigDecimal getBalance() throws JSONRPC2SessionException {
BigDecimal balance = null;
JSONObject result = rpcCall("getbalance", null);
if (result != null) {
balance = BigDecimal.valueOf(Long.valueOf("" + result.get("balance")), 12);
//balance = String.valueOf(result.get("balance"));
}
return balance;
}
private JSONObject rpcCall(String method, List<Object> params) throws JSONRPC2SessionException {
JSONRPC2Request request = new JSONRPC2Request(method, params, ++requestId);
JSONRPC2Response response = rpcSession.send(request);
JSONObject result = null;
if (response.indicatesSuccess()) {
result = (JSONObject) response.getResult();
} else {
// TODO: Throw exception
System.err.println(response.getError().getMessage());
}
return result;
}
}
BasicAuthenicator.java
public class BasicAuthenticator implements ConnectionConfigurator
{
public void configure(HttpURLConnection connection)
{
connection.addRequestProperty("Authorization", "Basic QWxhZGRpbjpPcGVuU2VzYW1l");
}
}