目录
请求响应流程
Get请求方式举例
代码:
public class Test {
public static void main(String[] args) {
System.out.println(doGet("http://www.baidu.com"));
}
/**
* 测试get请求方式
*
* @param link 链接
* @return 请求返回值
* @author 明快de玄米61
* @date 2021/09/05
*/
private static String doGet(String link) {
HttpURLConnection connection = null;
InputStream in = null;
BufferedReader reader = null;
try {
// 构造一个URL对象
URL url = new URL(link);
// 获取URLConnection对象
connection = (HttpURLConnection) url.openConnection();
// getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用connect()也可以)
in = connection.getInputStream();
// 通过InputStreamReader将字节流转换成字符串,在通过BufferedReader将字符流转换成自带缓冲流
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=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a> 京ICP证030173号 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
POST请求方式举例
例1:获取token
代码
public class Test {
public static void main(String[] args) {
System.out.println("token:" + doPost("接口地址", "root", "123456", "default"));
}
/**
* 测试post请求方式
* @author 明快de玄米61
* @date 2021/9/6 23:12
* @param apiUrl 接口地址
* @param username 用户名
* @param password 密码
* @param tenantUrl 租户标识
* @return
**/
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 url = new URL(apiUrl);
// 获取URLConnection对象
conn = (HttpURLConnection) url.openConnection();
// 限制socket等待建立连接的时间,超时将会抛出java.net.SocketTimeoutException
conn.setConnectTimeout(3000);
// 限制输入流等待数据到达的时间,超时将会抛出java.net.SocketTimeoutException
conn.setReadTimeout(3000);
// 设定请求的方法为"POST",默认是GET
conn.setRequestMethod("POST");
// 设置传送的内容类型是json格式
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 接收的内容类型也是json格式
conn.setRequestProperty("Accept", "application/json;charset=utf-8");
// 设置是否从httpUrlConnection读入,默认情况下是true
conn.setDoInput(true);
// 由于URLConnection在默认的情况下不允许输出,所以在请求输出流之前必须调用setDoOutput(true)。为一个HTTP URL将doOutput设置为true时,请求方法将由GET变为POST
conn.setDoOutput(true);
// 是否使用缓存,Post方式不能使用缓存
conn.setUseCaches(false);
// 准备数据
JSONObject json = new JSONObject();
json.put("username", username);
json.put("password", DigestUtils.md5Hex(password));
json.put("tenantUrl", tenantUrl);
// 返回一个OutputStream,可以用来写入数据传送给服务器
out = conn.getOutputStream();
// 将数据写入到输出流中
out.write(json.toString().getBytes(StandardCharsets.UTF_8));
// 刷新管道
out.flush();
// 建立连接
conn.connect();
// 判断数字响应码是否是200
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;
}
}