使用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的例子相比,最大的區別就在於請求參數的封裝上面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章