Subjects.java
import lombok.Data;
import java.util.List;
@Data
public class Subjects {
/**
* 主题id
*/
private Long id;
/**
* 主题内容
*/
private String theme;
/**
* 得票数
*/
private Long vote;
/**
* 浏览量
*/
private Long visit;
/**
* 创建日期
*/
private String createdate;
}
HttpRequest工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
//for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
//}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = 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)");
// 发送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;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
MessageUtil.java包含getpost和解析json
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.security.auth.Subject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
public class MessageUtil {
public static void main(String[] args) throws Exception {
Random random = new Random();
String code = "#code#=";
for (int i = 0;i < 6;i++){
code+=random.nextInt(10);
}
System.out.println(code);
//String myurl = "http://v.juhe.cn/sms/send?mobile=18233545556&tpl_id=194894&tpl_value="+ URLEncoder.encode(code,"utf-8") +"&key=1b46cef759c9bf970ce5a15ded0b4c37";
//String result =getUrl(myurl);
//System.out.println(result);
//==================================get请求=================
//String getMessageUrl = "http://127.0.0.1:8080/index222";
//String getResult = getUrl(getMessageUrl);
//System.out.println(getResult);
//String getResult2 = HttpRequest.sendGet(getMessageUrl,null);
//System.out.println(getResult2);
初始list
//List parse = (List) JSONArray.parse(getResult2);
//System.out.println(parse);
换list
//List subjectsList = null;
//subjectsList = parse;
list中map
//Map map = new HashMap();
结果list
//List<Subjects> resultList = new ArrayList<>();
转成map或者pojo
//for (Object o : subjectsList) {
// map = (Map) o;
// System.out.println(map.toString());
// Subjects subjects = JSON.parseObject(o.toString(),Subjects.class);
// resultList.add(subjects);
//}
//System.out.println("最终链表+对象"+resultList);
list分页
//PageHelper.startPage(2,1);
//PageInfo pageInfo =new PageInfo<>(resultList);
//System.out.println("分页之后对象" + pageInfo);
//=======================以上是get请求================
//post插入
String postMessageUrl = "http://127.0.0.1:80/air/addair";
JSONObject jsonObject = new JSONObject();
jsonObject.put("monitoringStation", "哈哈a");
jsonObject.put("pm10","20");
String s = jsonObject.toString();
//本文方法
//String postresut = sendPost(postMessageUrl,s);
//System.out.println(postresut);
//工具类方法
String s1 = MessageUtil.sendPost(postMessageUrl, s);
System.out.println(s1);
}
//Java发送HTTP的get请求
public static String getUrl(String myurl){
try {
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // 设置该连接是可以输出的
connection.setRequestMethod("GET"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) { // 读取数据
result.append(line + "\n");
}
connection.disconnect();
//System.out.println(result.toString());
return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String sendPost(String url,String param){
OutputStreamWriter out =null;
BufferedReader reader = null;
String response = "";
//创建连接
try {
URL httpUrl = null; //HTTP URL类 用这个类来创建连接
//创建URL
httpUrl = new URL(url);
//建立连接
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("connection", "keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//POST请求
out = new OutputStreamWriter(
conn.getOutputStream());
out.write(param);
out.flush();
//读取响应
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
response+=lines;
}
reader.close();
// 断开连接
conn.disconnect();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return response;
}
}
pom.xml
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!--<dependency>-->
<!-- <groupId>org.json</groupId>-->
<!-- <artifactId>json</artifactId>-->
<!-- <version>20200518</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
product.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Product implements Serializable {
private Integer pid;
private String pname;
private String marketPrice;
private String shopPrice;
private String pimage;
//@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
//@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date pdate;
private String pdesc;
}
后台方法
//测试api调用
@GetMapping("/index222")
@ResponseBody
public List index222(){
List<Subjects> all = subjectsService.findAll();
return all;
}
//3.执行添加操作
//测试post操作
@PostMapping("/addair")
@ResponseBody
public Integer doAdd(@RequestBody Air air){
//2.执行添加
Integer count = airService.save(air);
return count;
}
air.java
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
public class Air {
private Long id;
private Long districtId;
//@NotNull(message = "检测时间不能为空!")
//@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date monitorTime;
private Long pm10;
private Long pm25;
private String monitoringStation;
private Date lastModifyTime;
private String dname;
}