• HttpClient模拟http请求


    pom.xml中引入依赖

     

    <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient-osgi</artifactId>
            </dependency>

    ApiConsts.java

    public interface ApiConsts {
    
        int ApiTimeout = 10000;
        Charset ApiCharset = Charset.defaultCharset();
        String ApiCharsetName = ApiCharset.name();
        String DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
    
    }

    HttpUtils.java

    import org.apache.http.Header;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.fluent.Request;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.message.BasicHeader;
    import org.springframework.stereotype.Component;
    /**
     * 
     * @author wanjun
     *
     */
    @Component
    public class HttpUtils {
    
        private static Header[] DefaultJSONHeader = new Header[] {
                new BasicHeader("Content-Type", "application/json; charset=" + ApiConsts.ApiCharsetName) };
    
        private static Header[] getDefaultJSONHeaderWithCookie(String cookcie) {
            return DefaultJSONHeader = new Header[] {
                    new BasicHeader("Content-Type", "application/json; charset=" + ApiConsts.ApiCharsetName),
                    new BasicHeader("Cookie", cookcie) };
        };
    
        public String doPost(String apiUrl, String requestBody, String cookie) throws Exception {
            try {
                int timeout = ApiConsts.ApiTimeout;
                System.out.println("=============== [HTTP POST] ================");
                System.out.println("URL:" + apiUrl + ", timeout:" + timeout + "ms");
                System.out.println("Request Body:" + requestBody);
                String reply = Request.Post(apiUrl).socketTimeout(timeout).connectTimeout(timeout)
                        .body(new StringEntity(requestBody, ApiConsts.ApiCharset))
                        .setHeaders(getDefaultJSONHeaderWithCookie(cookie)).execute().returnContent()
                        .asString(ApiConsts.ApiCharset);
    
                System.out.println("Response Body:" + reply + "
    ");
                return reply;
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            }
            return requestBody;
        }
    
        public String doGet(String apiUrl) throws Exception {
            try {
                int timeout = ApiConsts.ApiTimeout;
                System.out.println("=============== [HTTP GET] ================");
                System.out.println("URL:" + apiUrl + ", timeout:" + timeout + "ms");
    
                String reply = Request.Get(apiUrl).socketTimeout(timeout).connectTimeout(timeout).execute().returnContent()
                        .asString(ApiConsts.ApiCharset);
    
                System.out.println("Response Body:" + reply + "
    ");
                return reply;
    
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            }
            return apiUrl;
        }
    
    }

    测试:

    @RequestMapping("/getMoney")
        public String memberWithdrawal(String userName,String pwd,String money) throws Exception {
            UserInfo userInfo = userInfoMapper.queryUserInfoByUserName(userName);
            RequestParamBean param = newRequestParamBean(); 
            //param.set()
            //param.set()
         String response = httpUtils.doPost("url", JSON.toJSONString(getMoney), userInfo.getCookie()); return response; }       
  • 相关阅读:
    一文说透 Spring 循环依赖问题
    git修改已经push的commit message
    Connection Timeout 和CommandTimeout
    mvc 当中 [ValidateAntiForgeryToken] 的作用及用法
    mvc 当中 [ValidateAntiForgeryToken] 的作用及用法
    asp.net mvc与asp.net core Ajax删除操作delete中带ValidateAntiForgeryToken实例
    VS2017秘钥
    Sql server 2008 R2 配置管理工具服务显示远程过程调用失败:0x800706be
    SQL Server 2008找不到SQL Server配置管理器的问题
    如何为SQL Server2008添加登录账户并配置权限
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/12625798.html
Copyright © 2020-2023  润新知