Java访问restful接口
程序员文章站
2022-06-26 11:58:44
...
其实java访问restful接口和访问一般的接口一样的,案例如下:
private Map<String,String> getIpMap(Map<String, Object> map, String today) {
//json模板
String request_tpl = "{\"type-a\" : {\"properties\" : { \"value\" : {\"type\":\"long\"} }}}";
String targetURL = "http://10.10.10.10:9200/myindex/_search";
Map<String, String> resultmap = WebUtil.doPostJson(request_tpl, targetURL);
return resultmap ;
}
public static Map<String, String> doPostJson(String json, String url) {
Map<String, String> resultMap = new HashMap<String, String>();
int statusCode = -1;
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = null;
if ("https".equals(httpUrl.getProtocol())) {
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
} catch (Exception e) {
throw new IOException(e);
}
HttpsURLConnection connHttps = (HttpsURLConnection) httpUrl.openConnection();
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;// 默认都认证通过
}
});
conn = connHttps;
} else {
conn = (HttpURLConnection) httpUrl.openConnection();
}
conn.setRequestMethod("POST");//PUT,POST,GET
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
//
StringBuffer params = new StringBuffer();
params.append(json);
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);//
//获取响应码失败
statusCode = conn.getResponseCode();
System.out.println(statusCode);
String result = "";
if (statusCode >= 200 && statusCode <= 299 && conn.getInputStream() != null) {
result = getStreamAsString(conn.getInputStream(), DEFAULT_CHARSET);
}
System.out.println("result=" + result);
resultMap.put("statuscode", statusCode + "");
resultMap.put("msg", result);
} catch (Exception e) {
resultMap.put("statuscode", statusCode + "");
resultMap.put("msg", e.getMessage().substring(0,500));
e.printStackTrace();
}
return resultMap;
}
转载于:https://my.oschina.net/weiweiblog/blog/1826817