package com.restful.base;
import java.io.IOException;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class RestTemplate {
/**
* 调用 API
*
* @param parameters
* @return
*/
public static String doPost(String url, Map<String, Object> param) {
String result = "";
CloseableHttpClient httpCLient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(JSONObject.fromObject(param).toString(), "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(3000)
.setSocketTimeout(5000).build();
httpPost.setConfig(requestConfig);
HttpResponse response = httpCLient.execute(httpPost);
if (entity != null) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpCLient != null)
httpCLient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPost2(String url, Map<String, Object> param) {
String result = "";
CloseableHttpClient httpCLient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(JSONObject.fromObject(param).toString(), "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpCLient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
//throw new Exception("接口连接异常,接口状态" + response.getStatus());
return "error";
}
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpCLient != null)
httpCLient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}