import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
public class HttpClientUtil {
public static String doPost(String httpUrl, Map<String, Object> mapParam, Map<String, String> headParams) {
String encoding = "UTF-8";
String realContentType = "application/json";
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(15000);
connection.setReadTimeout(60000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", realContentType);
if (headParams != null) {
for (String key : headParams.keySet()) {
connection.setRequestProperty(key, headParams.get(key));
}
}
os = connection.getOutputStream();
String param = null;
ObjectMapper mapper = new ObjectMapper();
param = mapper.writeValueAsString(mapParam);
if (null != param && "" != param.trim()) {
os.write(param.getBytes());
}
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(is, encoding));
StringBuffer sbf = new StringBuffer();
Object var11 = null;
String temp;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (MalformedURLException var35) {
var35.printStackTrace();
} catch (IOException var36) {
var36.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException var34) {
var34.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException var33) {
var33.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException var32) {
var32.printStackTrace();
}
}
connection.disconnect();
}
return result;
}
}
public static String doPost(String httpUrl, MultiValueMap<String, Object> postParameters) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(httpUrl, r, String.class);
return result;
}
public static String doGet(String httpUrl, Map<String, String> headParams) {
HttpHeaders headers = new HttpHeaders();
if (headParams != null) {
for (String key : headParams.keySet()) {
headers.add(key, headParams.get(key));
}
}
RestTemplate restTemplate = new RestTemplate();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(null, headers);
ResponseEntity<String> exchange =
restTemplate.exchange(httpUrl, HttpMethod.GET, httpEntity, String.class);
return exchange.getBody();
}