HttpURLConnection 实现登录SpringBoot后台项目

这篇博客展示了如何使用SpringBoot的Controller处理POST请求,并通过HttpURLConnection实现客户端登录功能。Controller部分代码接收User对象,验证用户名和密码,然后设置响应头。而在HttpURLConnection的实现中,创建连接,发送JSON格式的登录信息,读取并打印响应头的token信息。
摘要由CSDN通过智能技术生成

首先是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();
    }
}

以上全部,可供参考哈!

好的,下面是一个简单的示例代码: ```java // 注册请求 public void register(String username, String password) { try { URL url = new URL("http://example.com/register.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); OutputStream os = conn.getOutputStream(); String data = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); os.write(data.getBytes()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 注册成功 } else { // 注册失败 } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } // 登录请求 public void login(String username, String password) { try { URL url = new URL("http://example.com/login.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); OutputStream os = conn.getOutputStream(); String data = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); os.write(data.getBytes()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 登录成功 } else { // 登录失败 } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } ``` 以上代码中,register() 方法用于发送注册请求,login() 方法用于发送登录请求。其中,需要替换的部分是请求的 URL 和参数,以及请求成功后的处理逻辑。注意,这里使用了 HttpURLConnection 类进行请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值