zoukankan      html  css  js  c++  java
  • 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; }       
  • 相关阅读:
    redis系列:分布式锁
    Netty实现高性能IOT服务器(Groza)之手撕MQTT协议篇上
    DelayQueue
    java内置锁实现锁住代码块方案(同一个对象或锁住整个类.class)
    Java的类加载机制
    数据库事务特性ACID
    MQ关于实现最终一致性分布式事务原理解析
    数据库分库分表容量划分建议参考阿里云DRDS原则
    异常解决:Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
    OpenResty 简介
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/12625798.html
Copyright © 2011-2022 走看看