Java代码模拟一个Post请求

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

}
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Java可以使用HttpURLConnection类来模拟HTTP接口的POST请求。具体步骤如下: 1. 创建URL对象,指定要请求的接口地址。 2. 调用URL对象的openConnection()方法,获取HttpURLConnection对象。 3. 设置HttpURLConnection对象的请求方法为POST。 4. 设置HttpURLConnection对象的请求头信息,包括Content-Type、User-Agent等。 5. 设置HttpURLConnection对象的输出流,用于向接口发送请求参数。 6. 发送请求参数到接口。 7. 获取HttpURLConnection对象的输入流,读取接口返回的数据。 8. 关闭输入流和输出流,释放资源。 示例代码如下: ``` URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("User-Agent", "Mozilla/5."); conn.setDoOutput(true); String requestBody = "{\"name\":\"张三\",\"age\":18}"; OutputStream os = conn.getOutputStream(); os.write(requestBody.getBytes()); os.flush(); os.close(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = br.readLine()) != null) { response.append(line); } br.close(); is.close(); conn.disconnect(); System.out.println(response.toString()); ``` 以上代码模拟一个向接口发送JSON格式请求参数的POST请求,并读取接口返回的数据。需要注意的是,请求头信息和请求参数的格式需要根据接口的要求进行设置。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白居不易.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值