java中調用第三方接口獲取數據的方式


//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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM