用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"));
}
}
上一篇: WebApi Post 后台无法获取参数
下一篇: Spring与Dao
推荐阅读
-
C# GET/POST 发送HTTP请求,自动提交表单,模拟网页登录/网页注册。填坑
-
PHP模拟发送POST请求之三、用Telnet和fsockopen()模拟发送POST信息,telnetfsockopen
-
django框架下用ajax发送post请求403forbidden解决方法
-
PHP模拟发送POST请求之三、用Telnet和fsockopen()模拟发送POST信息,telnetfsockopen
-
用RestTemplate模拟ajax登录,发送POST请求
-
PHP模拟发送POST请求之三、用Telnet和fsockopen模拟发送POST信息
-
PHP模拟发送POST请求之三、用Telnet和fsockopen模拟发送POST信息
-
C# GET/POST 发送HTTP请求,自动提交表单,模拟网页登录/网页注册。填坑