舉例說明JAVA調(diào)用第三方接口的GET/POST/PUT請(qǐng)求方式
GET請(qǐng)求
public static String doGet(String url, String charset){
System.out.println("請(qǐng)求的接口:"+url);
/**
* 1.生成HttpClient對(duì)象并設(shè)置參數(shù)
*/
HttpClient httpClient = new HttpClient();
//設(shè)置Http連接超時(shí)為5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/**
* 2.生成GetMethod對(duì)象并設(shè)置參數(shù)
*/
GetMethod getMethod = new GetMethod(url);
//設(shè)置get請(qǐng)求超時(shí)為5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//設(shè)置請(qǐng)求重試處理,用的是默認(rèn)的重試處理:請(qǐng)求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/**
* 3.執(zhí)行HTTP GET 請(qǐng)求
*/
try {
int statusCode = httpClient.executeMethod(getMethod);
/**
* 4.判斷訪問的狀態(tài)碼
*/
if (statusCode != HttpStatus.SC_OK){
System.err.println("請(qǐng)求出錯(cuò):" + getMethod.getStatusLine());
}
/**
* 5.處理HTTP響應(yīng)內(nèi)容
*/
//HTTP響應(yīng)頭部信息,這里簡(jiǎn)單打印
Header[] headers = getMethod.getResponseHeaders();
/* for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}*/
//讀取HTTP響應(yīng)內(nèi)容,這里簡(jiǎn)單打印網(wǎng)頁(yè)內(nèi)容
//讀取為字節(jié)數(shù)組
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("接口返回?cái)?shù)據(jù)為:" + response);
//讀取為InputStream,在網(wǎng)頁(yè)內(nèi)容數(shù)據(jù)量大時(shí)候推薦使用
//InputStream response = getMethod.getResponseBodyAsStream();
return response;
} catch (HttpException e) {
//發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問題
System.out.println("請(qǐng)檢查輸入的URL!");
e.printStackTrace();
return "調(diào)用GET請(qǐng)求失敗";
} catch (IOException e){
//發(fā)生網(wǎng)絡(luò)異常
System.out.println("發(fā)生網(wǎng)絡(luò)異常!");
e.printStackTrace();
return "調(diào)用GET請(qǐng)求失敗";
}finally {
/**
* 6.釋放連接
*/
getMethod.releaseConnection();
}
}//get請(qǐng)求示例
String result = HttpClientToInterface.doGet("http://127.0.0.1:8085/xxxx/xxxx?yy=yyyyyy&zz=zzzzzzz","UTF-8");POST請(qǐng)求
public static String doPost(String url, String charset){
System.out.println("請(qǐng)求的接口:"+url);
/**
* 1.生成HttpClient對(duì)象并設(shè)置參數(shù)
*/
HttpClient httpClient = new HttpClient();
//設(shè)置Http連接超時(shí)為5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/**
* 2.生成PostMethod對(duì)象并設(shè)置參數(shù)
*/
PostMethod postMethod = new PostMethod(url);
//設(shè)置post請(qǐng)求超時(shí)為5秒
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//設(shè)置請(qǐng)求重試處理,用的是默認(rèn)的重試處理:請(qǐng)求三次
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/**
* 3.執(zhí)行HTTP POST 請(qǐng)求
*/
try {
int statusCode = httpClient.executeMethod(postMethod);
/**
* 4.判斷訪問的狀態(tài)碼
*/
if (statusCode != HttpStatus.SC_OK){
System.err.println("請(qǐng)求出錯(cuò):" + postMethod.getStatusLine());
}
/**
* 5.處理HTTP響應(yīng)內(nèi)容
*/
//HTTP響應(yīng)頭部信息,這里簡(jiǎn)單打印
Header[] headers = postMethod.getResponseHeaders();
/* for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}*/
//讀取HTTP響應(yīng)內(nèi)容,這里簡(jiǎn)單打印網(wǎng)頁(yè)內(nèi)容
//讀取為字節(jié)數(shù)組
byte[] responseBody = postMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("接口返回?cái)?shù)據(jù)為:" + response);
//讀取為InputStream,在網(wǎng)頁(yè)內(nèi)容數(shù)據(jù)量大時(shí)候推薦使用
//InputStream response = getMethod.getResponseBodyAsStream();
return response;
} catch (HttpException e) {
//發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問題
System.out.println("請(qǐng)檢查輸入的URL!");
e.printStackTrace();
return "調(diào)用POST請(qǐng)求失敗";
} catch (IOException e){
//發(fā)生網(wǎng)絡(luò)異常
System.out.println("發(fā)生網(wǎng)絡(luò)異常!");
e.printStackTrace();
return "調(diào)用POST請(qǐng)求失敗";
}finally {
/**
* 6.釋放連接
*/
postMethod.releaseConnection();
}
}//post請(qǐng)求示例
String result = HttpClientToInterface.doPost("http://127.0.0.1:8085/xxxx/xxxx?yy=yyyyyy&zz=zzzzzzz","UTF-8");POST請(qǐng)求(JSON傳參)
public static String doPost(String url, JSONObject json){
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// 首先Header部分需要設(shè)定字符集為:uft-8
post.addHeader("Content-Type", "application/json;charset=utf-8");
// 此處也需要設(shè)定
post.setHeader("Accept", "*/*");
post.setHeader("Accept-Encoding", "gzip, deflate, br");
// post.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
post.setHeader("Connection", "keep-alive");
post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
post.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8"))); //設(shè)置請(qǐng)求參數(shù)
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == statusCode){
//返回String
String res = EntityUtils.toString(response.getEntity());
System.out.println(res);
return res;
}else{
return "調(diào)用POST請(qǐng)求失敗";
}
} catch (Exception e) {
e.printStackTrace();
return "調(diào)用POST請(qǐng)求失敗";
}
}//post請(qǐng)求示例-josn傳參
Map<String, Object> map = new HashMap<>();
map.put("xxxx", "xxxxxx");
map.put("xxxxx", "xxxxxx");
JSONObject json = new JSONObject(map);
//以post形式請(qǐng)求接口
String result = HttpClientToInterface.doPost("http://127.0.0.1:8085/xxxx/xxxxx/", json);
JSONObject jsonObject = JSONObject.parseObject(result);
String data = jsonObject.get("data").toString();PUT請(qǐng)求(傳TOKEN)
public static String doPut(String url,String token){
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut(url);
//設(shè)置編碼 , 設(shè)置token參數(shù)
httpPut.addHeader("Authentication", token);
// 首先Header部分需要設(shè)定字符集為:uft-8
httpPut.addHeader("Content-Type", "application/json;charset=utf-8");
// 此處也需要設(shè)定
httpPut.setHeader("Accept", "*/*");
httpPut.setHeader("Accept-Encoding", "gzip, deflate, br");
// post.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
httpPut.setHeader("Connection", "keep-alive");
httpPut.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
//設(shè)置請(qǐng)求參數(shù)
System.out.println("Executing request " + httpPut.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(httpPut, responseHandler);
System.out.println("接口返回?cái)?shù)據(jù)為:"+responseBody);
return responseBody;
} catch (IOException e) {
e.printStackTrace();
return "調(diào)用PUT請(qǐng)求失敗";
}
}//put請(qǐng)求示例
String result = HttpClientToInterface.doPut("http://127.0.0.1:8085/xxxx/xxxxx", token);總結(jié)
到此這篇關(guān)于JAVA調(diào)用第三方接口的GET/POST/PUT請(qǐng)求方式的文章就介紹到這了,更多相關(guān)JAVA調(diào)用第三方接口請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JAVA構(gòu)造方法/構(gòu)造器以及this使用方式
這篇文章主要介紹了JAVA構(gòu)造方法/構(gòu)造器以及this使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
MyBatis-Plus聯(lián)表查詢及分頁(yè)代碼舉例
本文介紹了mybatis-plus-join工具的使用,該工具可以簡(jiǎn)化mybatis-plus的聯(lián)表查詢,使得開發(fā)者可以以類似QueryWrapper的方式進(jìn)行聯(lián)表查詢,無需手動(dòng)編寫xml文件,感興趣的朋友跟隨小編一起看看吧2025-03-03
java stream中Collectors的用法實(shí)例精講
這篇文章主要為大家介紹了java stream中Collectors的用法實(shí)例精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
Java方法參數(shù)傳遞如何實(shí)現(xiàn)
這篇文章主要介紹了Java方法參數(shù)傳遞如何實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
Spring Boot使用Druid和監(jiān)控配置方法
Druid是Java語(yǔ)言中最好的數(shù)據(jù)庫(kù)連接池,并且能夠提供強(qiáng)大的監(jiān)控和擴(kuò)展功能。下面來說明如何在 Spring Boot 中配置使用Druid2017-04-04
AsyncHttpClient KeepAliveStrategy源碼流程解讀
這篇文章主要為大家介紹了AsyncHttpClient KeepAliveStrategy源碼流程解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
解決mybatis-plus新增數(shù)據(jù)自增ID變無序問題
這篇文章主要介紹了解決mybatis-plus新增數(shù)據(jù)自增ID變無序問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2023-07-07

