private static final String DEFAULT_CHARSET = "UTF-8";
/**
* 执行HTTP POST请求
* @param url url
* @param param 参数
* @return
*/
public static String httpPostWithJSON(String url, JSONObject param) {
CloseableHttpClient client = null;
try {
if(url == null || url.trim().length() == 0){
throw new Exception("URL is null");
}
HttpPost httpPost = new HttpPost(url);
client = HttpClients.createDefault();
if(param != null){
StringEntity entity = new StringEntity(param.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding(DEFAULT_CHARSET);
entity.setContentType("application/json");
// entity.setContentType("text/xml");
httpPost.setEntity(entity);
}
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(client);
}
return null;
}
/**
* 执行HTTP GET请求
* @param url url
* @param param 参数
* @return
*/
public static String httpGetWithJSON(String url, Map<String, ?> param) {
CloseableHttpClient client = null;
try {
if(url == null || url.trim().length() == 0){
throw new Exception("URL is null");
}
client = HttpClients.createDefault();
if(param != null){
StringBuffer sb = new StringBuffer("?");
for (String key : param.keySet()){
sb.append(key).append("=").append(param.get(key)).append("&");
}
url = url.concat(sb.toString());
url = url.substring(0, url.length()-1);
}
HttpGet httpGet = new HttpGet(url);
HttpResponse resp = client.execute(httpGet);
if(resp.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(client);
}
return null;
}
/**
* 关闭HTTP请求
* @param client
*/
private static void close(CloseableHttpClient client){
if(client == null){
return;
}
try {
client.close();
} catch (Exception e) {
}
}
使用时引入:
JSONObject param = new JSONObject();
param.put("paperNo", paperNo); // 身份证号
System.out.println("**************接口入参:"+param.toString());
String result = httpPostWithJSON("http://*****", param);
java http请求接口
最新推荐文章于 2024-05-06 17:06:45 发布