欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用RestTemplate模拟ajax登录,发送POST请求

程序员文章站 2022-05-07 12:08:06
...

代码如下:

package con.bd720.service;

import net.sf.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@RunWith(SpringRunner.class)
@SpringBootTest
public class CommTest {

    /* *
     * 功能描述 模拟ajax登录方法
     * @author duxiaod
     * @date 2019/4/11
     * @param [url, params]
     * @return [url, params]
     */
    public  static  JSONObject login(String url,MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求,将返回的结构使用JSONObject类格式化
        ResponseEntity<JSONObject> response = client.exchange(url, method, requestEntity, JSONObject.class);
       return  response.getBody();
    }

    @Test
    public void loginTest(){
        String url= "http://192.168.1.141:8085/a/login?_ajax";
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("username","jgfzr");
        params.add("password","111");
        params.add("mobileLogin","true");
        JSONObject result = login(url, params);
        System.out.println("success:"+result.get("success"));
        System.out.println("body:"+result.get("body"));
    }
}