java對接第三方接口的3種常用方式
在日常工作中,經(jīng)常需要跟第三方系統(tǒng)對接,我們做為客戶端,調(diào)用他們的接口進行業(yè)務(wù)處理,常用的幾種調(diào)用方式有:
1.原生的Java.net.HttpURLConnection(jdk);
2.再次封裝的HttpClient、CloseableHttpClient(Apache);
3.Spring提供的RestTemplate;
當(dāng)然還有其他工具類進行封裝的接口,比如hutool的HttpUtil工具類,里面除了post、get請求外,還有下載文件的方法downloadFile等。
HttpURLConnection調(diào)用方法
HTTP正文的內(nèi)容是通過OutputStream流寫入,向流中寫入的數(shù)據(jù)不會立即發(fā)送到網(wǎng)絡(luò),而是存在于內(nèi)存緩沖區(qū)中,待流關(guān)閉時,根據(jù)寫入的內(nèi)容生成HTTP正文。
調(diào)用getInputStream()方法時,會返回一個輸入流,用于從中讀取服務(wù)器對于HTTP請求的返回報文
@Slf4j public class HttpURLConnectionUtil { /** * * Description: 發(fā)送http請求發(fā)送post和json格式 * @param url 請求URL * @param params json格式的請求參數(shù) */ public static String doPost(String url, String params) throws Exception { OutputStreamWriter out = null; BufferedReader reader = null; StringBuffer response = new StringBuffer(); URL httpUrl = null; // HTTP URL類 用這個類來創(chuàng)建連接 try { // 創(chuàng)建URL httpUrl = new URL(url); log.info("--------發(fā)起Http Post 請求 ------------- url:" + url + "---------params:" + params); // 建立連接 HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); //設(shè)置請求的方法為"POST",默認是GET conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("connection", "keep-alive"); conn.setUseCaches(false);// 設(shè)置不要緩存 conn.setInstanceFollowRedirects(true); //由于URLConnection在默認的情況下不允許輸出,所以在請求輸出流之前必須調(diào)用setDoOutput(true) conn.setDoOutput(true); // 設(shè)置是否從httpUrlConnection讀入 conn.setDoInput(true); //設(shè)置超時時間 conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.connect(); // POST請求 out = new OutputStreamWriter(conn.getOutputStream()); out.write(params); out.flush(); // 讀取響應(yīng) reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String lines; while ((lines = reader.readLine()) != null) { response.append(lines); } reader.close(); // 斷開連接 conn.disconnect(); } catch (Exception e) { log.error("--------發(fā)起Http Post 請求 異常 {}-------------", e); throw new Exception(e); } // 使用finally塊來關(guān)閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (reader != null) { reader.close(); } } catch (IOException ex) { log.error(String.valueOf(ex)); } } return response.toString(); } }
CloseableHttpClient調(diào)用
CloseableHttpClient 是一個抽象類,實現(xiàn)了httpClient接口,也實現(xiàn)了java.io.Closeable;
支持連接池管理,可復(fù)用已建立的連接 PoolingHttpClientConnectionManager
通過 httpClient.close() 自動管理連接釋放
支持HTTPS訪問 HttpHost proxy = new HttpHost(“127.0.0.1”, 8080, “http”);
@Slf4j public class CloseableHttpClientUtil { /** *url 第三方接口地址 *json 傳入的報文體,可以是dto對象,string、json等 *header 額外傳入的請求頭參數(shù) */ public static String doPost(String url, Object json,Map<String,String> header) { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost httpPost= new HttpPost(url);//post請求類型 String result="";//返回結(jié)果 String requestJson="";//發(fā)送報文體 try { requestJson=JSONObject.toJSONString(json); log.info("發(fā)送地址:"+url+"發(fā)送報文:"+requestJson); //StringEntity s = new StringEntity(requestJson, Charset.forName("UTF-8")); StringEntity s= new StringEntity(requestJson, "UTF-8"); // post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中 httpPost.setHeader("Content-Type", "application/json;charset=utf8"); httpPost.setEntity(s); if(header!=null){ Set<String> strings = header.keySet(); for(String str:strings){ httpPost.setHeader(str,header.get(str)); } } HttpResponse res = httpclient.execute(httpPost); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(res.getEntity()); //也可以把返回的報文轉(zhuǎn)成json類型 // JSONObject response = JSONObject.parseObject(result); } } catch (Exception e) { throw new RuntimeException(e); } finally { //此處可以加入記錄日志的方法 // 關(guān)閉連接,釋放資源 if (httpclient!= null){ try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
RestTemplate調(diào)用
//可以在項目啟動類中添加RestTemplate 的bean,后續(xù)就可以在代碼中@Autowired引入。
@Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Slf4j @Component public class RestTemplateUtils { @Autowired private RestTemplate restTemplate; /** * get 請求 參數(shù)在url后面 http://xxxx?aa=xxx&page=0&size=10"; * @param urls * @return string */ public String doGetRequest(String urls) { URI uri = UriComponentsBuilder.fromUriString(urls).build().toUri(); log.info("請求接口:{}", urls); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> httpEntity = new HttpEntity<>(headers); //通用的方法exchange,這個方法需要你在調(diào)用的時候去指定請求類型,可以是get,post,也能是其它類型的請求 ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class); if (responseEntity == null) { return null; } log.info("返回報文:{}", JSON.toJSONString(responseEntity)); return responseEntity.getBody(); } /** * post 請求 參數(shù)在 request里; * @param url, request * @return string */ public String doPostRequest(String url, Object request){ URI uri = UriComponentsBuilder.fromUriString(url).build().toUri(); String requestStr= JSONObject.toJSONString(request); log.info("請求接口:{}, 請求報文:{}", url, requestStr); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> httpEntity = new HttpEntity<>(requestStr, headers); ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class); if (responseEntity == null) { return null; } String seqResult = ""; try { if(responseEntity.getBody() != null ) { if(responseEntity.getBody().contains("9001")) { seqResult = new String(responseEntity.getBody().getBytes("ISO8859-1"),"utf-8"); }else { seqResult = new String(responseEntity.getBody().getBytes(),"utf-8"); } } log.info("返回報文:{}", seqResult); } catch (UnsupportedEncodingException e) { log.error("接口返回異常", e); } return seqResult; } }
總結(jié)
到此這篇關(guān)于java對接第三方接口的3種常用方式的文章就介紹到這了,更多相關(guān)java對接第三方接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IntelliJ IDEA導(dǎo)入Gradle項目的方法
這篇文章主要介紹了IntelliJ IDEA導(dǎo)入Gradle項目的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03新手小白學(xué)JAVA 日期類Date SimpleDateFormat Calendar(入門)
本文主要介紹了JAVA 日期類Date SimpleDateFormat Calendar,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10Java實現(xiàn)郵箱發(fā)送功能實例(阿里云郵箱推送)
這篇文章主要給大家介紹了關(guān)于Java實現(xiàn)郵箱發(fā)送功能的相關(guān)資料,利用阿里云郵箱推送,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09Java并發(fā)工具之CountDownLatch使用詳解
這篇文章主要介紹了Java并發(fā)工具之CountDownLatch使用詳解,通過使用 CountDownLatch可以使當(dāng)前線程阻塞,等待其他線程完成給定任務(wù),可以類比旅游團導(dǎo)游要等待所有的游客到齊后才能去下一個景點,需要的朋友可以參考下2023-12-12Spring?component-scan?XML配置與@ComponentScan注解配置
這篇文章主要介紹了Spring?component-scan?XML配置與@ComponentScan注解配置,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09intellij idea如何將web項目打成war包的實現(xiàn)
這篇文章主要介紹了intellij idea如何將web項目打成war包的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07