使用HttpClient类发起post或get请求例程

上一篇博客已经详细介绍过了关于http协议的相关内容,本篇给出post和get请求的代码样例。

需要导入的类有这些:

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
get的代码,参数直接拼接在url里面就行了。
 HttpGet httpGet = new HttpGet(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appid + "&secret="
                        + appsecret);
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsons = JSONObject.parseObject(result);///fromObject(result);
        String expires_in = jsons.getString("expires_in");

上面的例子中请求返回的对象是json格式的字符串,所以要先转换成JSONObject对象,然后久可以使用了。

post的代码,参数需要封装成JSONObject对象。

 HttpPost httpPost = new HttpPost(
                "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + access_token);
        JSONObject param = new JSONObject();
        param.put("touser", openid);
        param.put("template_id", templateId);
        param.put("form_id", formId);
        param.put("data", data);
StringEntity stringEntity = new StringEntity(param.toString());//param参数,可以为"key1=value1&key2=value2"的一串字符串
        stringEntity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(stringEntity);
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpPost);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsons = JSONObject.parseObject(result);///fromObject(result);
        String errcode = jsons.getString("errcode");

可以看出post的例子和get的例子相比,最大的区别就在于请求参数的封装上面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值