//get請求方式
private String getInfo(Map<String, Object> params,String URL) {
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString=null;
try {
// 創建uri
URIBuilder builder = new URIBuilder(URL);
if (params != null) {
for (String key : params.keySet()) {
builder.addParameter(key, params.get(key).toString());
}
}
URI uri = builder.build();
// 創建http GET請求
HttpGet httpGet = new HttpGet(uri);
// 執行請求
response = httpclient.execute(httpGet);
// 判斷返回狀態是否為200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
//post請求方式
private String getInfo(Map<String, Object> params, String URL) {
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = null;
try {
// 創建uri
URIBuilder builder = new URIBuilder(URL);
if (params != null) {
for (String key : params.keySet()) {
builder.addParameter(key, params.get(key).toString());
}
}
URI uri = builder.build();
// 創建http POST請求
HttpPost httpPost = new HttpPost(uri);
// 執行請求
response = httpclient.execute(httpPost);
// 判斷返回狀態是否為200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(),"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
//傳送json類型參數的post請求
private String getCarMapInfo(String json, String URL) {
// 創建Httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = null;
try {
// 創建Http Post請求
HttpPost httpPost = new HttpPost(URL);
// 創建請求內容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 執行http請求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}