java简单操作
Easul Lv6

简单的http请求

JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package ml.lightly.demo.gradle.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
* 需要引入的gradle依赖
* implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.41'
*/
public class HttpUtil {
/**
* 组装json数组的方法
* @return JSONArray 返回一个json数组对象
*/
private JSONArray assembleJson() {
/*
json对象 {"id": "123", "name": "zhangsan"}
json数组 [{"id": "123", "name": "zhangsan"}, {"id": "124", "name": "zhangsan"}]
*/
JSONObject json = new JSONObject(); // 用于存json键值对
JSONArray jsonArr = new JSONArray(); // 用于存json对象的数据

// json对象使用put方法来存键值对
// json对象值也可以是json数组
json.put("id", "zhangsan");

/*
JSONObject和JSONArray都可以使用toString()转为字符串
*/
jsonArr.add(json); // json数组用add方法来存json对象
return jsonArr;
}

/**
* HTTP响应为JSON字符串,将JSON字符串解析为Map进行操作
* @param String response HTTP响应的JSON字符串
*/
private String getJsonValue(String response) {
// 抑制定义泛型的提示
@SuppressWarnings("rawtypes")
// 使用JSON.parse方法将字符串转换为对象
Map responseMap = (Map)JSON.parse(response);
// 使用Map的get方法获取某个键的值
String value = (String)responseMap.get("message");
return value;
}

/**
* 使用Http的POST方法发送json数据包给某API
* @param JSONArray jsonArr
* @return String 返回响应的body数据
*/
private String doHttpPOSTSendJson(JSONArray jsonArr) {
OutputStream out = null; // 创建输出流对象
BufferedReader reader = null; // 创建读取对象
HttpURLConnection conn = null; // 创建Http连接
StringBuilder response = new StringBuilder(); // 用于存大量的字符串


try {
// 创建一个关于api链接的URL对象,
// 如果是GET请求直接在URL后边以?添加数据即可
URL url = new URL("https://www.fastmock.site/mock/530cb59823947e8648f90191e9072021/easul/post_test");
conn = (HttpURLConnection)url.openConnection();
// 设置为true,则可以给输出流写入信息。GET请求可以不设该项
conn.setDoOutput(true);
// 设置为true,则可以从输入流读入信息。GET请求可以不设该项
conn.setDoInput(true);
// 设置请求的方法,GET,POST,DELETE等
conn.setRequestMethod("POST");
// setRequestProperty() 设置请求头
// 描述客户端希望接收的响应body的数据类型
conn.setRequestProperty("accept", "*/*");
// 设置发送请求格式为json,也可以为表单或者其他形式。GET请求可以不设该项
conn.setRequestProperty("Content-Type", "application/json");
// 设置连接的状态
conn.setRequestProperty("connnection", "keep-alive");
// 有需要的话这里设置token在header中
// conn.setRequestProperty("token", "");
// 在header中设置cookie的形式
// conn.setRequestProperty("Cookie", myCookie);
// 设置是否使用缓存
conn.setUseCaches(false);
// 进行HTTP连接
conn.connect();

// 获取HTTP连接后的输出流对象
out = conn.getOutputStream();
// 将json数组字符串以UTF-8的二进制写入输出流中
out.write(jsonArr.toString().getBytes("utf-8"));
// 刷新输出流,将数据传递到API方
out.flush();

// 获取API响应的输入流,并以UTF-8的格式读取到BufferedReader对象中。否则可能乱码
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String lines;
// 用lines一行一行接收读取回来的数据,如果仍有数据,则不为null,把数据写入StringBuilder中
while ((lines = reader.readLine()) != null) {
response.append(lines);
}


// 获取API响应头字段
Map<String, List<String>> headerMap = conn.getHeaderFields();
// 获取里边的cookie
List<String> cookieList = headerMap.get("Set-Cookie");
StringBuilder builder = new StringBuilder();
for (String str : cookieList) {
builder.append(str);
}
System.out.println(builder.toString());
// 进行头字段的遍历。当然也可以直接使用get(key)来获取某个键的值
for (String key : headerMap.keySet()) {
System.out.println(key + "--->" + headerMap.get(key));
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (IOException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return response.toString();
}

public void httpTest() {
JSONArray postDataArr = assembleJson();
String result = doHttpPOSTSendJson(postDataArr);
System.out.println(result);
String message = getJsonValue(result);
System.out.println(message);
}
}

简单数据库操作

JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package ml.lightly.demo.gradle.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* 需要引入的gradle依赖
* mysql implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.16'
* sql server implementation group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '8.2.2.jre11'
*/
public class DatabaseUtil {
// JDBC驱动引擎,这里使用的是SQL Server的JDBC
// MySQL的JDBC: com.mysql.cj.jdbc.Driver
private static final String DRIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 数据库访问链接。这里为SQL Server的数据库访问格式
// MySQL的数据库访问链接(需要加上海时区,否则报错): "jdbc:mysql://localhost:3306/cas?useSSL=false&serverTimezone=CTT"
private static String dbURL = "jdbc:sqlserver://127.0.0.1;DatabaseName=test";
// 数据库用户名
private static String dbUser = "sa";
// 数据库密码
private static String dbPass = "sa";

/**
* 进行数据库的SQL操作
*/
public void doSqlOperation() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 将JDBC进行装载
Class.forName(DRIVER_NAME);
// 进行数据库连接
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// 创建数据库SQL操作对象
stmt = conn.createStatement();
// 编写SQL语句。SQL Server中的数据库需要写dbo.表名
// SQL语句不能加分号,否则报错
String sql = "select count(ID) from dbo.mytable where sync = 1";
// 查询语句使用executionQuery方法操作。返回ResultSet对象
rs = stmt.executeQuery(sql);
// 使用ResultSet对象的next方法查看是否还有下一行数据
if (rs.next()) {
int newDataRows = rs.getInt(1); // 获取int类型的数据
System.out.println(newDataRows);
}

// 增删改使用executeUpdate方法操作,返回影响了几行数据。如果为0,则说明没有进行任何数据修改。
sql = "update dbo.mytable set sync = 1 where ID = 0";
int execResult = stmt.executeUpdate(sql);
System.out.println(execResult);

} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

读取和写入properties文件

JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ml.lightly.demo.gradle.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class PropertiesUtil {
// 创建配置对象
Properties properties = new Properties();
Properties saveLocaton = new Properties();
// 定义配置文件的绝对路径
private final static String CURRENT_LOCATION_PATH = PropertiesUtil.class.getResource("/").getPath()+"api.properties";

/**
* 获取配置文件中某键的值
*/
public void getProperty() {
// 使用当前类加载器获取文件流。配置文件在resources中。resources文件夹为顶层目录
InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("api.properties");
try {
// 加载获取的文件流
properties.load(inputStream);
// 通过键获得配置文件中对应的值
String dbIP = properties.get("sqlServerIpAddress").toString();
System.out.println(dbIP);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 在新文件中存储某键值
*/
public void setProperty() {
OutputStream output = null;
try {
// 读取文件流
saveLocaton.load(new FileInputStream(CURRENT_LOCATION_PATH));
// 打开文件的输出流
output = new FileOutputStream(CURRENT_LOCATION_PATH);
// 设置对应的属性
saveLocaton.setProperty("sqlServerIpAddress", "12");
// 存储该属性到文件中,并加入描述信息
saveLocaton.store(output, "current location record");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭输出流资源
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
 评论