java遠程調(diào)用接口、URL的方式代碼
一:httpUrlConnection
1.獲取HttpURLConnection連接對象
/** * 獲取HttpURLConnection連接對象 * @param url 遠程調(diào)用的url * @return */ public static HttpURLConnection getHttpURLConnection(String url){ try { //建立連接 URL httpUrl = new URL(url); HttpURLConnection urlConnection =(HttpURLConnection)httpUrl.openConnection(); //向文件所在服務(wù)器發(fā)送標(biāo)識信息,模擬瀏覽器 urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"); return urlConnection; } catch (IOException e) { e.printStackTrace(); return null; } }
2.遠程調(diào)用代碼
/** * 遠程調(diào)用登錄接口 */ public void accessLoginUrl(){ //遠程調(diào)用接口的url String loginUrl = "http://localhost:8989/login/doLogin"; OutputStream outputStream = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; try { //獲取壓測接口的userTicket URL url = new URL(loginUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //登錄是post請求 connection.setRequestMethod("POST"); //post請求需要設(shè)置接口返回的數(shù)據(jù),所以設(shè)置為true connection.setDoOutput(true); //參數(shù)userId和密碼 String param = "mobile=" + 13100000000000L + "&password=" + "123456"; //獲取登錄接口返回的流文件 outputStream = connection.getOutputStream(); outputStream.write(param.getBytes(StandardCharsets.UTF_8)); outputStream.flush(); inputStream = connection.getInputStream(); byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) >= 0){ byteArrayOutputStream.write(buffer, 0, len); } //獲取響應(yīng)結(jié)果 String response = byteArrayOutputStream.toString(); ObjectMapper objectMapper = new ObjectMapper(); RespBean respBean = objectMapper.readValue(response, RespBean.class); String userTicket = (String) respBean.getObject(); System.out.println("遠程調(diào)用接口的返回值"+userTicket); //userTicket就是遠程接口返回的值 } catch (IOException e) { e.printStackTrace(); } finally { if(byteArrayOutputStream != null){ try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(outputStream != null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
二:RestTemplate
2.1 什么是RestTemplate
1.spring 框架提供的 RestTemplate 類可用于在應(yīng)用中調(diào)用 rest 服務(wù),它簡化了與 http 服務(wù)的通信方式,統(tǒng)一了 RESTful 的標(biāo)準,封裝了 http 鏈接, 我們只需要傳入 url 及返回值類型即可。相較于之前常用的 HttpClient,RestTemplate 是一種更優(yōu)雅的調(diào)用 RESTful 服務(wù)的方式。
2.在 Spring 應(yīng)用程序中訪問第三方 REST 服務(wù)與使用 Spring RestTemplate 類有關(guān)。RestTemplate 類的設(shè)計原則與許多其他 Spring 模板類(例如 JdbcTemplate、JmsTemplate)相同,為執(zhí)行復(fù)雜任務(wù)提供了一種具有默認行為的簡化方法。
3.RestTemplate 默認依賴 JDK 提供 http 連接的能力(HttpURLConnection),如果有需要的話也可以通過 setRequestFactory 方法替換為例如 Apache HttpComponents、Netty 或 OkHttp 等其它 HTTP library。
4.考慮到 RestTemplate 類是為調(diào)用 REST 服務(wù)而設(shè)計的,因此它的主要方法與 REST 的基礎(chǔ)緊密相連就不足為奇了,后者是 HTTP 協(xié)議的方法:HEAD、GET、POST、PUT、DELETE 和 OPTIONS。例如,RestTemplate 類具有 headForHeaders()、getForObject()、postForObject()、put()和 delete()等方法。
2.2 配置RestTemplate
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(){ SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); //解決401報錯時,報java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode requestFactory.setOutputStreaming(false); RestTemplate restTemplate = new RestTemplate(requestFactory); restTemplate.setErrorHandler(new RtErrorHandler()); return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(5000); factory.setConnectTimeout(15000); return factory; }
2.2 RestTemplate 添加請求頭headers和請求體body
HttpHeaders header = new HttpHeaders(); header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id"); header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name"); header.set("Authorization", "authorization"); HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);
- header 為需要設(shè)置的請求頭
- AssetProcessVo為需要遠程調(diào)用接口傳遞的參數(shù)
2.3 示例代碼
/** * 遠程調(diào)用登錄接口 */ public void accessLoginUrl(){ HttpHeaders header = new HttpHeaders(); header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id"); header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name"); header.set("Authorization", "authorization"); HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header); ResponseEntity<ByteArrayOutputStream> exchange; try { //保存案件名稱后,啟動工作流 exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ByteArrayOutputStream.class); if (exchange.getStatusCodeValue() == 200) { String response = byteArrayOutputStream.toString(); ObjectMapper objectMapper = new ObjectMapper(); RespBean respBean = objectMapper.readValue(response, RespBean.class); } } catch (RestClientException e) { e.printStackTrace(); }
三:HttpClient
3.1 導(dǎo)入依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
3.2 使用方法
1,創(chuàng)建HttpClient對象;
2,指定請求URL,并創(chuàng)建請求對象,如果是get請求則創(chuàng)建HttpGet對象,post則創(chuàng)建HttpPost對象;
3,如果請求帶有參數(shù),對于get請求可直接在URL中加上參數(shù)請求,或者使用setParam(HetpParams params)方法設(shè)置參數(shù),對于HttpPost請求,可使用setParam(HetpParams params)方法或者調(diào)用setEntity(HttpEntity entity)方法設(shè)置參數(shù);
4,調(diào)用httpClient的execute(HttpUriRequest request)執(zhí)行請求,返回結(jié)果是一個response對象;
5,通過response的getHeaders(String name)或getAllHeaders()可獲得請求頭部信息,getEntity()方法獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。
3.3 代碼實現(xiàn)
package com.cnzz.demo.remote.rpc; import com.alibaba.fastjson.JSONObject; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import java.io.IOException; /** * ************************************************************ * Copyright ? 2020 cnzz Inc.All rights reserved. * ** * ************************************************************ * * @program: demo * @description: * @author: cnzz * @create: 2020-12-23 17:41 **/ public class HttpClientUtil { /** * httpClient的get請求方式 * 使用GetMethod來訪問一個URL對應(yīng)的網(wǎng)頁實現(xiàn)步驟: * 1.生成一個HttpClient對象并設(shè)置相應(yīng)的參數(shù); * 2.生成一個GetMethod對象并設(shè)置響應(yīng)的參數(shù); * 3.用HttpClient生成的對象來執(zhí)行GetMethod生成的Get方法; * 4.處理響應(yīng)狀態(tài)碼; * 5.若響應(yīng)正常,處理HTTP響應(yīng)內(nèi)容; * 6.釋放連接。 * @param url * @param charset * @return */ public static String doGet(String url, String charset) { //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("-----------response:" + response); //讀取為InputStream,在網(wǎng)頁內(nèi)容數(shù)據(jù)量大時候推薦使用 //InputStream response = getMethod.getResponseBodyAsStream(); } catch (HttpException e) { //發(fā)生致命的異常,可能是協(xié)議不對或者返回的內(nèi)容有問題 System.out.println("請檢查輸入的URL!"); e.printStackTrace(); } catch (IOException e) { //發(fā)生網(wǎng)絡(luò)異常 System.out.println("發(fā)生網(wǎng)絡(luò)異常!"); } finally { //6.釋放連接 getMethod.releaseConnection(); } return response; } /** * post請求 * @param url * @param json * @return */ public static String doPost(String url, JSONObject json){ HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("accept", "*/*"); postMethod.addRequestHeader("connection", "Keep-Alive"); //設(shè)置json格式傳送 postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK"); //必須設(shè)置下面這個Header postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); //添加請求參數(shù) postMethod.addParameter("commentId", json.getString("commentId")); String res = ""; try { int code = httpClient.executeMethod(postMethod); if (code == 200){ res = postMethod.getResponseBodyAsString(); System.out.println(res); } } catch (IOException e) { e.printStackTrace(); } return res; } public static void main(String[] args) { System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=telPhone", "GBK")); System.out.println("-----------分割線------------"); System.out.println("-----------分割線------------"); System.out.println("-----------分割線------------"); JSONObject jsonObject = new JSONObject(); jsonObject.put("commentId", "telPhone"); System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject)); } }
總結(jié)
到此這篇關(guān)于java遠程調(diào)用接口、URL的文章就介紹到這了,更多相關(guān)java遠程調(diào)用接口URL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Cache監(jiān)控配置與使用規(guī)范的建議
這篇文章主要介紹了Spring Cache監(jiān)控配置與使用規(guī)范的建議,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Mybatis-plus解決兼容oracle批量插入的示例詳解
Mybatis-Plus 是一個 MyBatis 的增強工具,提供無侵入、損耗小的 CRUD 操作,本文給大家介紹了Mybatis-plus解決兼容oracle批量插入,文中通過大家介紹的非常詳細,需要的朋友可以參考下2024-11-11使用FeignClient進行微服務(wù)交互方式(微服務(wù)接口互相調(diào)用)
這篇文章主要介紹了使用FeignClient進行微服務(wù)交互方式(微服務(wù)接口互相調(diào)用),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03mybatis QueryWrapper的條件構(gòu)造之a(chǎn)pply、last、select解析
這篇文章主要介紹了mybatis QueryWrapper的條件構(gòu)造之a(chǎn)pply、last、select,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03java核心編程之文件過濾類FileFilter和FilenameFilter
這篇文章主要為大家詳細介紹了java文件過濾類FileFilter和FilenameFilter,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08SpringBoot中使用異步調(diào)度程序的高級方法
本文主要介紹了SpringBoot中使用異步調(diào)度程序的高級方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07