1、使用HttpURLConnection调用url
public static String postJson(String callbackUrl, Map params, int connectTimeout, int readTimeout) {
String result = "";
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
String json = JSON.toJSONString(params);
try {
URL url = new URL(callbackUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(connectTimeout);
httpURLConnection.setReadTimeout(readTimeout);
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
os.close();
if (httpURLConnection.getResponseCode() == 200) {
reader = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream())
);
String data = "";
StringBuilder builder = new StringBuilder();
while ((data = reader.readLine()) != null) {
builder.append(data);
}
result = builder.toString();
}
} catch (Exception e) {
log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + params, e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
2、HttpClient调用
public static String postJson2(String callbackUrl, CallBackDTO callBackDTO, int connectTimeout, int readTimeout){
String jsonString = JSON.toJSONString(callBackDTO);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(callbackUrl);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setSocketTimeout(readTimeout).build();
httpPost.setConfig(requestConfig);
StringEntity stringEntity = null;
CloseableHttpResponse response = null;
String res = null;
try {
stringEntity = new StringEntity(jsonString, "UTF-8");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity httpEntity = null;
httpEntity = response.getEntity();
res = EntityUtils.toString(httpEntity, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + callBackDTO, e);
e.printStackTrace();
} catch (ClientProtocolException e) {
log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + callBackDTO, e);
e.printStackTrace();
} catch (IOException e) {
log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + callBackDTO, e);
e.printStackTrace();
} finally{
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
}