Skip to content

Instantly share code, notes, and snippets.

@gutenye
Created August 6, 2016 08:50
Show Gist options
  • Save gutenye/a7185005c0c6c887c851c430655fec77 to your computer and use it in GitHub Desktop.
Save gutenye/a7185005c0c6c887c851c430655fec77 to your computer and use it in GitHub Desktop.
import java.net.*;
import java.io.*;
public class Hello {
public static void main(String[] args) {
HttpURLConnection connection = null;
String data = "{\"jsonrpc\": \"1.0\", \"method\": \"getaccountaddress\", \"params\": [\"a\"] }";
String username = "rpc";
String password = "rpc123";
try {
URL url = new URL("http://home.guten.me:9332");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Content-Length", Integer.toString(data.getBytes().length));
// 采用HTTP Basic Auth, 这里需要一个Base64 encoding, 我没有库, 运行起来就401 UnAuthorize 错误, 你应该会的
/*
String encoding = Base64Encoder.encode(username+":"+password);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
*/
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes(data);
wr.close();
//Get Response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment