在上一篇博客已经详细介绍过了关于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的例子相比,最大的区别就在于请求参数的封装上面。