第一步(封装Http请求):
Get:
public static String sendGet(String url, String param) {
String result = “”;
BufferedReader in = null;
try {
String urlName = url;
if (param != null && !"".equals(param)) {
urlName = url + “?” + param;
}
// String urlName = url + “?” + param;
URL realUrl = new URL(urlName);
// 打开和URL之间的连 ?
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属 ?
conn.setRequestProperty(“accept”, “/”);
conn.setRequestProperty(“connection”, “Keep-Alive”);
conn.setRequestProperty(“user-agent”, “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)”);
conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);
conn.setRequestMethod(“GET”);
// 建立实际的连 ?
conn.connect();
// 获取 ?有响应头字段
Map<String, List> map = conn.getHeaderFields();
// 遍历 ?有的响应头字 ?
// for (String key: map.keySet()) {
// }
// 定义BufferedReader输入流来读取URL的响 ?
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line; // “\n” +
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入 ?
finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
----------------------------------------------------------------------------------------------------------------
POST:
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = “”;
Authenticator.setDefault(new Authenticator() {
//验证账号密码
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“账号”, “密码”.toCharArray());
}
});
try {
URL realUrl = new URL(url);
// 打开和URL之间的连 ?
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属 ?
conn.setRequestProperty(“accept”, “/”);
conn.setRequestProperty(“connection”, “Keep-Alive”);
conn.setRequestProperty(“user-agent”, “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)”);
conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);
conn.setRequestMethod(“POST”);
// 发 送 POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发 ? 请求参 ?
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line; // “\n” +
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输出流 ? 输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
第二步(调用方法):
命令行如(curl):curl -v -u 账号:密码 --data-binary ‘{“jsonrpc”:“2.0”,“id”:“curltext”,“method”:“命令方法”}’ -H ‘content-type:application/json;’ http://127.0.0.1:8888
调方法即可:sendPost(“http://127.0.0.1:8888”,"{“jsonrpc”:“2.0”,“id”:“curltext”,“method”:“getblockchaininfo”}");