请求响应流程
Get请求方式举例
代码:
public class Test {
public static void main(String[] args) {
System.out.println(doGet("http://www.baidu.com"));
}
private static String doGet(String link) {
HttpURLConnection connection = null;
InputStream in = null;
BufferedReader reader = null;
try {
URL url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
结果:
<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=
POST请求方式举例
例1:获取token
代码
public class Test {
public static void main(String[] args) {
System.out.println("token:" + doPost("接口地址", "root", "123456", "default"));
}
private static String doPost(String apiUrl, String username, String password, String tenantUrl) {
HttpURLConnection conn = null;
OutputStream out = null;
InputStream in = null;
String idToken = null;
try {
URL url = new URL(apiUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("Accept", "application/json;charset=utf-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", DigestUtils.md5Hex(password));
json.put("tenantUrl", tenantUrl);
out = conn.getOutputStream();
out.write(json.toString().getBytes(StandardCharsets.UTF_8));
out.flush();
conn.connect();
int responseCode = conn.getResponseCode();
String result = "";
if (responseCode == 200) {
in = conn.getInputStream();
StringWriter sw = new StringWriter();
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
char[] buffer = new char[4096];
for (int n = 0; -1 != (n = reader.read(buffer)); ) {
sw.write(buffer, 0, n);
}
result = sw.toString();
if (result != null && !"".equals(result.trim())) {
JSONObject rjo = JSONObject.parseObject(result, Feature.OrderedField);
if (rjo != null && rjo.containsKey("retCode")) {
int retCode = rjo.getInteger("retCode");
if (retCode == 0 && rjo.containsKey("data")) {
JSONObject data = rjo.getJSONObject("data");
if (null != data && data.containsKey("idToken")) {
idToken = data.getString("idToken");
}
}
}
}
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
throw new RuntimeException("获取token出现连接/超时异常");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("获取token时执行内部代码时出现异常");
} finally {
try {
if (conn != null) {
conn.disconnect();
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return idToken;
}
}
结果
token:853b7c87-c16f-4e3b-96c4-9701fe3448ab
接口文档
Postman访问示例
例2:获取知识图谱信息
代码
public class Test {
public static void main(String[] args) {
System.out.println("图谱结果:" + doPost("接口地址", "实例id", "token令牌", "图谱实例数量"));
}
private static String doPost(String apiUrl, String instanceId, String idToken, Integer number) {
HttpURLConnection conn = null;
OutputStream out = null;
InputStream in = null;
String result = null;
try {
URL url = new URL(apiUrl);
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("Accept", "application/json;charset=utf-8");
conn.setRequestProperty("Authorization", "Bearer " + idToken);
conn.setDoInput(true);
conn.setDoOutput(true);
JSONObject json = new JSONObject();
json.put("pageNum", 0);
json.put("pageSize", number);
JSONObject data = new JSONObject();
String[] status = { "on" };
data.put("status", status);
String[] instanceIdSet = { instanceId };
data.put("instanceIdSet", instanceIdSet);
String[] checked = { "on" };
data.put("checked", checked);
json.put("data", data);
out = conn.getOutputStream();
out.write(json.toString().getBytes("utf-8"));
out.flush();
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
in = conn.getInputStream();
StringWriter sw = new StringWriter();
InputStreamReader reader = new InputStreamReader(in, "utf-8");
char[] buffer = new char[4096];
for (int n = 0; -1 != (n = reader.read(buffer));) {
sw.write(buffer, 0, n);
}
result = sw.toString();
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
throw new RuntimeException("调用获取图谱接口出现连接/超时异常");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("调用获取图谱接口执行内部代码时出现异常");
} finally {
try {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
}
接口文档
Postman访问示例
参考
1、详解HttpURLConnection
2、URLConnection
|