Java代码模拟一个Post请求
我们常用的http请求无非GET和POST。在springboot项目中,我们如果想要测试一段代码无非就是项目跑起来,然后在浏览器中通过输入url,看浏览器中(按F12)控制台是否响应成功,以及看IDEA控制台的打印内容。
但是在浏览器中输入url,GET请求很好模拟,无非是本机ip+服务端口+springboot项目中在controller层配置的@RequestMapping(“/访问路径”)。而POST请求就不是那么好模拟的了,因为POST请求一般包含参数,参数以JSON格式封装在请求体中,有其对应的请求头。那么POST请求该如何模拟呢?代码如下所示:
依赖:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
这个依赖使用的目的是通过一个JSONObject的类封装我们的参数。然后剩下的依赖,在前面的HttpClient的学习笔记中有提到。
模拟Post请求代码如下:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
public class PostTest {
/**
* 模拟Post请求,进行url测试
*/
@Test
public void testPostRequest() {
String url = "http://127.0.0.1:8081/business/user/record/query";
//请求ti
JSONObject parammap = new JSONObject();
parammap.put("userid",123456);
parammap.put("username", "xiaoming");
parammap.put("appname", "myapp");
parammap.put("queryDate","20220321");
String str = doPost(url, parammap.toJSONString());
// 输出响应内容
System.out.println(str);
}
public String doPost(String url ,String json) {
//创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String res = "";
try {
// 创建 httppost请求
HttpPost post = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(entity);
// 执行http请求
response = httpClient.execute(post);
res = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
}
}
更新:
将常用的get、post请求封装为一个工具类,代码如下:
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public final class HttpUtil {
/**
* 连接客户端
*/
private static final CloseableHttpClient HTTP_CLIENT;
/**
* 最大连接数
*/
private static final int MAX = 50;
private HttpUtil() {}
static {
PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager() {};
manager.setMaxTotal(MAX);
HTTP_CLIENT = HttpClients.custom().setConnectionManager(manager).build();
}
public static String httpGet(String url) throws IOException {
HttpGet get = new HttpGet(url);
try (CloseableHttpResponse response = HTTP_CLIENT.execute(get)) {
return EntityUtils.toString(response.getEntity());
}
}
public static String httpGet(String url, Map<String, String> headers) throws IOException {
HttpGet get = new HttpGet(url);
headers.forEach(get::addHeader);
try (CloseableHttpResponse response = HTTP_CLIENT.execute(get)) {
return EntityUtils.toString(response.getEntity());
}
}
public static String httpPost(String url, Map<String, String> params, Map<String, String> headers)
throws IOException {
HttpPost post = new HttpPost(url);
headers.forEach(post::addHeader);
List<NameValuePair> parameters = new ArrayList<>();
params.forEach((key, value) -> parameters.add(new BasicNameValuePair(key, value)));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
post.setEntity(entity);
try (CloseableHttpResponse response = HTTP_CLIENT.execute(post)) {
return EntityUtils.toString(response.getEntity());
}
}
public static String httpPostJson(String url, String body, Map<String, String> headers) throws IOException {
HttpPost post = new HttpPost(url);
headers.forEach(post::addHeader);
post.setEntity(new StringEntity(body, "utf-8"));
try (CloseableHttpResponse response = HTTP_CLIENT.execute(post)) {
return EntityUtils.toString(response.getEntity());
}
}
}