/**
* 发起post请求
*
* @param url 地址
* @param jsonParams json格式的参数
* @throws Exception
*/
JSONObject httpPost(String url ,String jsonParams) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity stringEntity = new StringEntity(jsonParams);
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
InputStream inputStream = resEntity.getContent();
int size = inputStream.available();
byte[] bs = new byte[size];
inputStream.read(bs);
String message = new String(bs, StandardCharsets.UTF_8);
return JSONObject.parseObject(message);
}
/**
* 发起Get请求
*
* @param url 地址
* @param jsonParams json格式的参数
* @throws Exception
*/
JSONObject httpGet(String url ,String jsonParams) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity stringEntity = new StringEntity(jsonParams);
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
HttpEntity entity = httpClient.execute(httpGet).getEntity();
InputStream inputStream = entity.getContent();
int size = entity.getContent().available();
byte[] bs = new byte[size];
inputStream.read(bs);
String message = new String(bs, StandardCharsets.UTF_8);
return JSONObject.parseObject(message);
}
/***
* 发起get请求
*/
public static JSONObject doGet(String urls) throws Exception {
URL url = new URL(urls);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
//获取返回的字符
InputStream inputStream = connection.getInputStream();
int size = inputStream.available();
byte[] bs = new byte[size];
inputStream.read(bs);
String message = new String(bs, StandardCharsets.UTF_8);
return JSONObject.parseObject(message);
}