代码如下:
// 准备client
CloseableHttpClient client = HttpClients.createDefault();
// 准备HttpPost请求,[get请求自己去看HttpGet对象,已经他需要封装的参数]
HttpPost doPost = new HttpPost("https://sms.yunpian.com/v2/sms/single_send.json");
// 准备参数
ArrayList<NameValuePair> arrayList = new ArrayList<>();
NameValuePair pair1 = new BasicNameValuePair("k1", "v1");
NameValuePair pair2 = new BasicNameValuePair("k2", "v2");
NameValuePair pair3 = new BasicNameValuePair("k3", "v3");
arrayList.add(pair1);
arrayList.add(pair2);
arrayList.add(pair3);
// 将参数封装到FormEntity中放入httppost的entity中
doPost.setEntity(new UrlEncodedFormEntity(arrayList, "UTF-8"));
// client调用执行请求,拿到返回对象
CloseableHttpResponse response = client.execute(doPost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// 用utils工具类拿到返回结果的字符串形式
String s = EntityUtils.toString(entity, "UTF-8");
// 形如:{"http_status_code":400,"code":-1,"msg":"非法的apikey","detail":"请检查您的apikey是否正确,或者账户已经失效"}
// 解析成HashMap,拿到需要的部分信息
HashMap hashMap = JSONObject.parseObject(s, HashMap.class);
// 最后对这些信息做逻辑处理
System.out.println("http_status_code: " + hashMap.get("http_status_code"));
System.out.println("code: " + hashMap.get("code"));
System.out.println("msg: " + hashMap.get("msg"));
System.out.println("detail: " + hashMap.get("detail"));
// 注:CloseableHttpClient
// 注:CloseableHttpResponse
// 注意这两个对象关闭问题,以及异常处理
// 注:CloseableHttpClient
// 注:CloseableHttpResponse
// 注意这两个对象关闭问题,以及异常处理