post请求
public static String doPostByJSONObect(String url, JSONObject args) throws Exception {
if (StringUtils.isEmpty(url))
throw new Exception("地址为空");
// URI m_url = new URI(url);
// URLDecoder.decode(url,"UTF-8");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(args.toJSONString(), "UTF-8");
httpPost.setEntity(se);
/*或使用
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entrys = args.entrySet();
for (Map.Entry<String, String> entry : entrys) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
*/
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String text = EntityUtils.toString(httpEntity);
System.out.print("Content Text :: ");
System.out.println(text);
return text;
} catch (ClientProtocolException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (httpResponse != null)
httpResponse.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
get请求
public static String doGetAsStr(String url) throws Exception {
if (StringUtils.isEmpty(url))
throw new Exception("地址为空");
// URI m_url = new URI(url);
// URLDecoder.decode(url,"UTF-8");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String text = EntityUtils.toString(httpEntity);
return text;
} catch (ClientProtocolException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (httpResponse != null)
httpResponse.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}