Can't connect to Bitcoin wallet with JSON-RPC - java

I'm trying to connect to Bitcoin wallet from Java. But i get network exception: Server redirected too many times. I would be very glad if someone helps me understand.
Here's my code:
public static void SetupRPC() {
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("admin", "admin".toCharArray());
}
});
URL serverURL = null;
try {
serverURL = new URL("http://127.0.0.1:44843");
} catch (MalformedURLException e) {
System.err.println(e.getMessage());
}
JSONRPC2Session mySession = new JSONRPC2Session(serverURL);
String method = "getinfo";
int requestID = 0;
JSONRPC2Request request = new JSONRPC2Request(method, requestID);
// Send request
JSONRPC2Response response = null;
try {
response = mySession.send(request);
} catch (JSONRPC2SessionException e) {
System.err.println(e.getMessage());
}
if (response.indicatesSuccess())
System.out.println(response.getResult());
else
System.out.println(response.getError().getMessage());
}
And .conf file:
rpcuser="admin"
rpcpassword="admin"
rpcallowip=*
rpcport=44843
server=1
daemon=1
listen=1
rpcconnect=127.0.0.1

If these are your code and .conf, then remove the " in your conf file. Or add \" to your string.
So this
return new PasswordAuthentication ("\"admin\"", "\"admin\"".toCharArray());
or this
rpcuser="admin"
rpcpassword="admin"
Also you cannot have # in your password or username(which was my case).
After I found this I got an Invalid JSON-RPC 2.0 response.
My solution was to change !jsonObject.containsKey("error") to (!jsonObject.containsKey("error") || jsonObject.get("error") == null) in the function
public JSONRPC2Response parseJSONRPC2Response(final String jsonString) which is located in the base of JSONRPC 2.0 in JSONRPC2Parser.java somewhere around line 495.
EDIT: This was on the DogeCoin-QT, so maybe the Bitcoin-QT does not have this problem.

Ok, i solve this problem:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pass".toCharArray());
}
});
String uri = "http://127.0.0.1:8332";
String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"method\":\"getbalance\"}";
String contentType = "application/json";
HttpURLConnection connection = null;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length));
connection.setUseCaches(true);
connection.setDoInput(true);
OutputStream out = connection.getOutputStream();
out.write(requestBody.getBytes());
out.flush();
out.close();
} catch (IOException ioE) {
connection.disconnect();
ioE.printStackTrace();
}
try {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response);
} else {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}

Related

Java HttpURLConnection invoke remote server and returned 500 status

I want to invoke remote server using HttpURLConnection, here is my function:
public String invokeAwvsServer(String api, String param, String method){
System.out.println(api+param);
BufferedReader reader = null;
HttpURLConnection connection = null;
OutputStreamWriter out = null;
try {
URL url = new URL(api);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth", apiKey);
connection.connect();
if(method.equalsIgnoreCase("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuffer res = new StringBuffer();
while ((line = reader.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
I use this function in its own class and works well, but if I call it in other class ,the remote server return 500 status code and JVM throws exception like:
java.io.IOException: Server returned HTTP response code: 500 for URL:...
What`s the reason?Thanks a lot:)

java get response from PayU api poland

I'm trying to integrate payu poland payment system to my website but cant get success response. Website done by jsp. Here is link that payu gave for help click im using "create a new order" for configuration. But its not retrieving any answer. Could anywane help me? Here is my jsp code:
`public static String sendPostRequest2(String requestUrl, String payload, String x, String y) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
writer.write(payload);
}
connection.setRequestProperty(x, y);
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
connection.disconnect();
} catch (IOException e) {
try {
URL url = new URL(requestUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
jsonString.append(new RuntimeException(e.getMessage()));
} catch (MalformedURLException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
}
}
return jsonString.toString();
}
public static String get() {
String x = "";
String payload2 = "{ 'notifyUrl': 'https://your.eshop.com/notify', 'customerIp': '127.0.0.1', 'merchantPosId': '145227', 'description': 'RTV market', 'currencyCode': 'PLN', 'totalAmount': '21000', 'products': [ { 'name': 'Wireless mouse', 'unitPrice': '15000', 'quantity': '1' }, { 'name': 'HDMI cable', 'unitPrice': '6000', 'quantity': '1' } ]}";
String requestUrl2 = "https://secure.payu.com/api/v2_1/orders/";
x += sendPostRequest2(requestUrl2, payload2, "Authorization", "Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd");
return x;
}`
set the redirect turn off after that you will get the json response. So in your java code set redirect false.
connection.setInstanceFollowRedirects(false);

How can I write an api post request from Java to c#

Recently I needed to move some code from Java to C#.
This is one of the methods that I couldn't rewrite... can someone help me?
public static String coreApiPostRequest(URL url, String input) {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
String responseMessage=null;
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
responseMessage = output;
}
conn.disconnect();
return responseMessage;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Java - Put Request

I'm trying to perform a "PUT" but nothing happens, i don't catch any exception either.
Here is what I've tried:
String destinationUrl = 'http://stash.myDomain.com/rest/api/1.0/projects/myProj/permissions/users?name=myUser&permission=PROJECT_WRITE';
URL url = null;
try {
url = new URL(destinationUrl)
} catch (MalformedURLException exception) {
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try {
String userpass = STASH_USERNAME + ":" + STASH_PASSWORD;
String basicAuth = "Basic " + converter.printBase64Binary(userpass.getBytes());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("PUT");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Authorization", basicAuth)
//httpURLConnection.setRequestProperty("Content-Type", "application/json");
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes("Hello");
} catch (IOException excepption) {
excepption.printStackTrace();
} finally {
if (dataOutputStream != null) {
try {
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Any idea what should i do ?

FileNotFoundException on HttpsURLConnection with POST and unmutable doOutput variable

I'm trying to POST some data to an https url, in my android application, in order to get a json format response.
I'm facing two problems:
is = conn.getInputStream();
throws
java.io.FileNotFoundException
I don't get if i do something wrong with HttpsURLConnection.
The second problem arose when i debug the code (used eclipse); I set a breakpoint after
conn.setDoOutput(true);
and, when inspecting conn values, I see that the variable doOutput remain set to false and type GET.
My method for https POST is the following, where POSTData is a class extending ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
A little update: apparently eclipse debug lied to me, running and debugging on netbeans shows a POST connection. Error seems to be related to parameters i'm passing to the url.
FileNotFoundException means that the URL you posted to doesn't exist, or couldn't be mapped to a servlet. It is the result of an HTTP 404 status code.
Don't worry about what you see in the debugger if it doesn't agree with how the program behaves. If doOutput really wasn't enabled, you would get an exception obtaining the output stream.

Categories