postmanUtils工具类,模拟postman的get,post请求

package com.demo.common;

import org.apache.http.HttpEntity;
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.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;


@Configuration
public class PostMethod {
    @Value("${post.url}")
    private  String posturl;

    @Value("${post.param}")
    private String postparam;
    @Value("${get.url}")
    private  String geturl;

    @PostConstruct
    public void   postutil() throws  Exception{
        System.out.println("正在执行post请求------------------------------------------");

        System.out.println("读取posturl------------------"+posturl);
        System.out.println("读取postparam------------------"+postparam);

        //1、打开postman
//这一步相当于运行main方法。
//2、创建request连接 3、填写url和请求方式
        HttpPost httpPost = new HttpPost(posturl);
//2.1 额外设置Content-Type请求头
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
//4、如果有参数添加参数
        CloseableHttpClient client = HttpClients.createDefault();
        httpPost.setEntity(new StringEntity(postparam,"UTF-8"));
//5、点击发送按钮,发送请求  6、获取响应报文
        CloseableHttpResponse response = client.execute(httpPost);
//7、格式化响应报文
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
//8、在控制台输出报文
        System.out.println("请求结果是----------------------"+result);
        System.out.println("执行post请求结束------------------------------------------");

    }

    @PostConstruct
    public void   getutil() throws  Exception{
        System.out.println("get------------------------------------------");
        System.out.println("读取posturl------------------"+geturl);

        //1、打开postman
//这一步相当于运行main方法。
//2、创建request连接 3、填写url和请求方式
        HttpGet get = new HttpGet(geturl);
//4、如果有参数添加参数 get请求不需要参数,省略
        CloseableHttpClient client = HttpClients.createDefault();
//5、点击发送按钮,发送请求 6、获取响应报文
        CloseableHttpResponse response = client.execute(get);
//7、格式化响应报文
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
//8、在控制台输出报文
         System.out.println("请求结果是----------------------"+result);
        System.out.println("执行get请求结束------------------------------------------");

    }

}


版权声明:本文为weixin_40074861原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。