舉例說明JAVA調(diào)用第三方接口的GET/POST/PUT請求方式
更新時間:2024年01月09日 09:05:29 作者:英勇的小王同志
在日常工作和學(xué)習(xí)中,有很多地方都需要發(fā)送請求,這篇文章主要給大家介紹了關(guān)于JAVA調(diào)用第三方接口的GET/POST/PUT請求方式的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
GET請求
public static String doGet(String url, String charset){
System.out.println("請求的接口:"+url);
/**
* 1.生成HttpClient對象并設(shè)置參數(shù)
*/
HttpClient httpClient = new HttpClient();
//設(shè)置Http連接超時為5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/**
* 2.生成GetMethod對象并設(shè)置參數(shù)
*/
GetMethod getMethod = new GetMethod(url);
//設(shè)置get請求超時為5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//設(shè)置請求重試處理,用的是默認的重試處理:請求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/**
* 3.執(zhí)行HTTP GET 請求
*/
try {
int statusCode = httpClient.executeMethod(getMethod);
/**
* 4.判斷訪問的狀態(tài)碼
*/
if (statusCode != HttpStatus.SC_OK){
System.err.println("請求出錯:" + getMethod.getStatusLine());
}
/**
* 5.處理HTTP響應(yīng)內(nèi)容
*/
//HTTP響應(yīng)頭部信息,這里簡單打印
Header[] headers = getMethod.getResponseHeaders();
/* for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}*/
//讀取HTTP響應(yīng)內(nèi)容,這里簡單打印網(wǎng)頁內(nèi)容
//讀取為字節(jié)數(shù)組
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("接口返回數(shù)據(jù)為:" + response);
//讀取為InputStream,在網(wǎng)頁內(nèi)容數(shù)據(jù)量大時候推薦使用
//InputStream response = getMethod.getResponseBodyAsStream();
return response;
} catch (HttpException e) {
//發(fā)生致命的異常,可能是協(xié)議不對或者返回的內(nèi)容有問題
System.out.println("請檢查輸入的URL!");
e.printStackTrace();
return "調(diào)用GET請求失敗";
} catch (IOException e){
//發(fā)生網(wǎng)絡(luò)異常
System.out.println("發(fā)生網(wǎng)絡(luò)異常!");
e.printStackTrace();
return "調(diào)用GET請求失敗";
}finally {
/**
* 6.釋放連接
*/
getMethod.releaseConnection();
}
}//get請求示例
String result = HttpClientToInterface.doGet("http://127.0.0.1:8085/xxxx/xxxx?yy=yyyyyy&zz=zzzzzzz","UTF-8");POST請求
public static String doPost(String url, String charset){
System.out.println("請求的接口:"+url);
/**
* 1.生成HttpClient對象并設(shè)置參數(shù)
*/
HttpClient httpClient = new HttpClient();
//設(shè)置Http連接超時為5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
/**
* 2.生成PostMethod對象并設(shè)置參數(shù)
*/
PostMethod postMethod = new PostMethod(url);
//設(shè)置post請求超時為5秒
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//設(shè)置請求重試處理,用的是默認的重試處理:請求三次
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
/**
* 3.執(zhí)行HTTP POST 請求
*/
try {
int statusCode = httpClient.executeMethod(postMethod);
/**
* 4.判斷訪問的狀態(tài)碼
*/
if (statusCode != HttpStatus.SC_OK){
System.err.println("請求出錯:" + postMethod.getStatusLine());
}
/**
* 5.處理HTTP響應(yīng)內(nèi)容
*/
//HTTP響應(yīng)頭部信息,這里簡單打印
Header[] headers = postMethod.getResponseHeaders();
/* for (Header h: headers){
System.out.println(h.getName() + "---------------" + h.getValue());
}*/
//讀取HTTP響應(yīng)內(nèi)容,這里簡單打印網(wǎng)頁內(nèi)容
//讀取為字節(jié)數(shù)組
byte[] responseBody = postMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("接口返回數(shù)據(jù)為:" + response);
//讀取為InputStream,在網(wǎng)頁內(nèi)容數(shù)據(jù)量大時候推薦使用
//InputStream response = getMethod.getResponseBodyAsStream();
return response;
} catch (HttpException e) {
//發(fā)生致命的異常,可能是協(xié)議不對或者返回的內(nèi)容有問題
System.out.println("請檢查輸入的URL!");
e.printStackTrace();
return "調(diào)用POST請求失敗";
} catch (IOException e){
//發(fā)生網(wǎng)絡(luò)異常
System.out.println("發(fā)生網(wǎng)絡(luò)異常!");
e.printStackTrace();
return "調(diào)用POST請求失敗";
}finally {
/**
* 6.釋放連接
*/
postMethod.releaseConnection();
}
}//post請求示例
String result = HttpClientToInterface.doPost("http://127.0.0.1:8085/xxxx/xxxx?yy=yyyyyy&zz=zzzzzzz","UTF-8");POST請求(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è)置請求參數(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請求失敗";
}
} catch (Exception e) {
e.printStackTrace();
return "調(diào)用POST請求失敗";
}
}//post請求示例-josn傳參
Map<String, Object> map = new HashMap<>();
map.put("xxxx", "xxxxxx");
map.put("xxxxx", "xxxxxx");
JSONObject json = new JSONObject(map);
//以post形式請求接口
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請求(傳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è)置請求參數(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("接口返回數(shù)據(jù)為:"+responseBody);
return responseBody;
} catch (IOException e) {
e.printStackTrace();
return "調(diào)用PUT請求失敗";
}
}//put請求示例
String result = HttpClientToInterface.doPut("http://127.0.0.1:8085/xxxx/xxxxx", token);總結(jié)
到此這篇關(guān)于JAVA調(diào)用第三方接口的GET/POST/PUT請求方式的文章就介紹到這了,更多相關(guān)JAVA調(diào)用第三方接口請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JAVA構(gòu)造方法/構(gòu)造器以及this使用方式
這篇文章主要介紹了JAVA構(gòu)造方法/構(gòu)造器以及this使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
Spring Boot使用Druid和監(jiān)控配置方法
Druid是Java語言中最好的數(shù)據(jù)庫連接池,并且能夠提供強大的監(jiān)控和擴展功能。下面來說明如何在 Spring Boot 中配置使用Druid2017-04-04
AsyncHttpClient KeepAliveStrategy源碼流程解讀
這篇文章主要為大家介紹了AsyncHttpClient KeepAliveStrategy源碼流程解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
解決mybatis-plus新增數(shù)據(jù)自增ID變無序問題
這篇文章主要介紹了解決mybatis-plus新增數(shù)據(jù)自增ID變無序問題,具有很好的參考價值,希望對大家有所幫助。2023-07-07

