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

代码如下:

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 params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求,将返回的结构使用JSONObject类格式化
        ResponseEntity 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 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"));
    }
}

 

你可能感兴趣的:(用RestTemplate模拟ajax登录,发送POST请求)