使用HttpClient调用接口登录获取cookie查询

HttpClient发送Post请求有2种方式传参方式StringEntity 和 UrlEncodedFormEntity (UrlEncodedFormEntity继承了StringEntity)

其中StringEntity,相比UrlEncodedFormEntity更加灵活,UrlEncodedFormEntity的构造方法限制死了(Iterable<? extends NameValuePair> )只能用NameValuePair。

但是UrlEncodedFormEntity更适用于传统表单格式,

在项目中遇到的调用别人的查询接口需要先进行登录在调用。并且传参格式需要form表单提交。封装了如下方法.

  /**
     * 封装HTTP POST方法
     *
     * @param url(要查询的地址)
	 * @param paramMap(传入参数)
     * @throws ClientProtocolException
     * @throws IOException
     */
 public static String postCookieTonken(String url,Map<String, String> paramMap) throws ClientProtocolException, IOException {
        String name = "用户名"; //
        String password = "密码"; //
        // 全局请求设置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        // 创建cookie store的本地实例
        CookieStore cookieStore = new BasicCookieStore();
        // 创建HttpClient上下文
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);
        // 创建一个HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse res = null;

        try {
           //建立一个NameValuePair(简单名称值对节点类型)数组,用于存储欲传送的参数
            List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();
            valuePairs.add(new BasicNameValuePair("username", name));
            valuePairs.add(new BasicNameValuePair("password", password));
          
			//UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
            //转换成form表单的编码格式
            entity.setContentType("application/x-www-form-urlencoded");
            // 创建一个post请求
            HttpPost post = new HttpPost("登录的url");
            // 往post里面放入数据
            post.setEntity(entity);
            //请求访问url
            res = httpClient.execute(post, context);
           //访问接口返回的参数,cookie的话已经存入CookieStore,
            String httpEntityContent = getHttpEntityContent(res);
			//这里建立了连接会被一直保持着所以要释放一下资源
 	        res.close();
			 // 获取到了cooki在构造一个新的get请求,用来调用查询的接口
			 //先吧参数放入List<NameValuePair> 
             List<NameValuePair> formparams = setHttpParams(paramMap);
              //用URLEncodedUtils解析参数拼接到请求地址上
             String param = URLEncodedUtils.format(formparams, "UTF-8");
             HttpGet newGet = new HttpGet(url+"?"+param);
             //访问接口这里登录成功的话cookie已经在context里面了
             res = httpClient.execute(newGet, context);
             //最后解析返回的参数
             String httpEntityContent = getHttpEntityContent(res);
	    	//这里建立了连接会被一直保持着所以要释放一下资源资源
            res.close();
            return httpEntityContent;
        } finally {
            httpClient.close();

        }



    }

还有的要接口要传入json字符对象的方法

  /**
     * 封装HTTP POST方法
     * @param url (调用的url)
     * @param paramMap (传入的参数)
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url,Map<String, String> paramMap ) throws ClientProtocolException, IOException {
        List<NameValuePair> formparams = setHttpParams(paramMap);
        String param = URLEncodedUtils.format(formparams, "UTF-8");
        HttpClient httpClient = HttpClients.createDefault();
        //创建post请求吧参数粘在后面PS:我也不知道为啥粘在后面参数才能传过去求解
        HttpPost httpPost = new HttpPost(url+"?"+param);
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        //解析格式并用StringEntity设置参数格式
        String datad = JSONObject.toJSONString(mapParamas);
        StringEntity params = new StringEntity(data,"UTF-8");
        params.setContentEncoding("UTF-8");
        params.setContentType("application/json;charset=UTF-8");
        //将参数放入post
        httpPost.setEntity(params);
        //调用接口
        HttpResponse response = httpClient.execute(httpPost);
        //解析返回参数
        String httpEntityContent = getHttpEntityContent(response);
        //最后连接终止
        httpPost.abort();
        return httpEntityContent;
    }

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值