首先是SpringBoot的controller,如下:
import cn.cheng.bean.User;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
@RestController
public class TestController {
@PostMapping("/getDate")
public String getDate(@RequestBody User user, HttpServletResponse response) {
if (user == null || !user.getUsername().equals("root") || !user.getPassword().equals("1234")) {
return "参数错误";
}
response.setHeader("authorization", "55555");
return "success";
}
}
接着是HttpURLConnection实现登录,并获取token信息,代码如下:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
public class DoMain {
public static void main(String args[]) {
new Thread(()->{
String data = "";
HttpURLConnection conn = null;
OutputStreamWriter osw = null;
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
conn = (HttpURLConnection) new URL("http://localhost:8080/getDate").openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
osw = new OutputStreamWriter(conn.getOutputStream());
osw.write("{\"username\": \"root\",\"password\": \"1234\"}");
osw.close();
Map<String, List<String>> map = conn.getHeaderFields();
System.out.println(map.get("authorization")+ "------------------");
if (conn.getResponseCode() == 200) {
bis = new BufferedInputStream(conn.getInputStream());
baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
if ((len = bis.read(buff)) != -1) {
baos.write(buff,0,len);
}
data = baos.toString();
System.out.println(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
}).start();
}
}
以上全部,可供参考哈!