HttpClient发送post请求调用接口,且方法体和body都设置参数

/**
     * post请求
     * @param url    请求地址
     * @param b    设置到body中的参数字节数组
     * @param map    参数map
     * @return    返回接口字符串
     * @throws Exception
     */
    public static String httpPost(String url, byte[] b, Map<String, String> map) throws Exception {
        // 返回body
        String body = "";
        // 1、创建一个htt客户端
        HttpClient httpClient = new DefaultHttpClient();
        // 2、创建一个HttpPost请求
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        post.setHeader("charset", "UTF-8");
        post.setEntity(new StringEntity("image=" + Base64AndUrlEncodeBytes(b)));
        // 5、设置header信息
        post.setHeader("X-Appid", APPID);
        post.setHeader("X-CurTime", getUTCTimeStr());
        post.setHeader("X-Param", Base64String(param));
        post.setHeader("X-CheckSum", MD5String(APIKey + getUTCTimeStr() + Base64String(param)));
        // post.setHeader("Connection", "close");
        // 设置参数
        if (map != null) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        }
        // 7、执行post请求操作,并拿到结果
        HttpResponse httpResponse = httpClient.execute(post);
        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, HTTP.UTF_8);
        }
        // EntityUtils.consume(entity);
        httpClient.getConnectionManager().shutdown();
        System.out.println(body.length());
        return body;
    }

maven依赖

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.1.2</version>
		</dependency>

该post请求方法中有其他的几个编码的方法,对参数编码是我调用的接口规定必须如此,因此对于参数的编码格式,还需要根据实际的api要求来进行设置。



————————————————————————————————————————

最后,庆祝自己大难不死。这个吊毛大货车,差点把我卷进车轮子下面。告诫广大网友,在马路上,一定要小心,远离大货车。

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值