Java調(diào)用第三方http接口的四種方式總結(jié)
前言
在實(shí)際開發(fā)過程中,我們經(jīng)常需要調(diào)用對方提供的接口或測試自己寫的接口是否合適。很多項(xiàng)目都會封裝規(guī)定好本身項(xiàng)目的接口規(guī)范,所以大多數(shù)需要去調(diào)用對方提供的接口或第三方接口(短信、天氣等)
①通過JDK網(wǎng)絡(luò)類Java.net.HttpURLConnection;
②通過common封裝好的HttpClient;
③通過Apache封裝好的CloseableHttpClient;
④通過SpringBoot-RestTemplate;
一、通過SpringBoot-RestTemplate方式(其余幾種的集大成者)
目前可以采用的調(diào)用第三方接口有:
- delete() : 在特定的URL上對資源執(zhí)行HTTP DELETE操作
- exchange() : 在URL上執(zhí)行特定的HTTP方法,返回包含對象的ResponseEntity,這個對象是從響應(yīng)體中映射得到的
- execute() : 在URL上執(zhí)行特定的HTTP方法,返回一個從響應(yīng)體映射得到的對象
- getForEntity() :發(fā)送一個HTTP GET請求,返回的ResponseEntity包含了響應(yīng)體所映射成的對象
- getForObject() :發(fā)送一個HTTP GET請求,返回的請求體將映射為一個對象
- postForEntity() :POST 數(shù)據(jù)到一個URL,返回包含一個對象的ResponseEntity,這個對象是從響應(yīng)體中映射得到的
- postForObject(): POST 數(shù)據(jù)到一個URL,返回根據(jù)響應(yīng)體匹配形成的對象
- headForHeaders() :發(fā)送HTTP HEAD請求,返回包含特定資源URL的HTTP頭
- optionsForAllow() :發(fā)送HTTP OPTIONS請求,返回對特定URL的Allow頭信息
- postForLocation() :POST 數(shù)據(jù)到一個URL,返回新創(chuàng)建資源的URL
- put() :PUT 資源到特定的URL
1.1、RestTemplateConfig.java類
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory){ return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory(){ SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(15000); factory.setReadTimeout(5000); return factory; } }
1.2、然后在Service類(RestTemplateToInterface )中注入使用
import com.alibaba.fastjson.JSONObject; import com.swordfall.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class RestTemplateToInterface { @Autowired private RestTemplate restTemplate; /** * 以get方式請求第三方http接口 getForEntity * @param url * @return */ public User doGetWith1(String url){ ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class); User user = responseEntity.getBody(); return user; } /** * 以get方式請求第三方http接口 getForObject * 返回值返回的是響應(yīng)體,省去了我們再去getBody() * @param url * @return */ public User doGetWith2(String url){ User user = restTemplate.getForObject(url, User.class); return user; } /** * 以post方式請求第三方http接口 postForEntity * @param url * @return */ public String doPostWith1(String url){ User user = new User("小白", 20); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class); String body = responseEntity.getBody(); return body; } /** * 以post方式請求第三方http接口 postForEntity * @param url * @return */ public String doPostWith2(String url){ User user = new User("小白", 20); String body = restTemplate.postForObject(url, user, String.class); return body; } /** * exchange * @return */ public String doExchange(String url, Integer age, String name){ //header參數(shù) HttpHeaders headers = new HttpHeaders(); String token = "asdfaf2322"; headers.add("authorization", token); headers.setContentType(MediaType.APPLICATION_JSON); //放入body中的json參數(shù) JSONObject obj = new JSONObject(); obj.put("age", age); obj.put("name", name); //組裝 HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers); ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class); String body = responseEntity.getBody(); return body; } }
二、通過JDK網(wǎng)絡(luò)類Java.net.HttpURLConnection
比較原始的一種調(diào)用做法,這里把get請求和post請求都統(tǒng)一放在一個方法里面
import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpUrlConnectionToInterface { /** * 以post或get方式調(diào)用對方接口方法, * @param pathUrl */ public static void doPostOrGet(String pathUrl, String data){ OutputStreamWriter out = null; BufferedReader br = null; String result = ""; try { URL url = new URL(pathUrl); //打開和url之間的連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //請求方式 conn.setRequestMethod("POST"); //conn.setRequestMethod("GET"); //設(shè)置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //DoOutput設(shè)置是否向httpUrlConnection輸出,DoInput設(shè)置是否從httpUrlConnection讀入,此外發(fā)送post請求必須設(shè)置這兩個 conn.setDoOutput(true); conn.setDoInput(true); /** * 下面的三句代碼,就是調(diào)用第三方http接口 */ //獲取URLConnection對象對應(yīng)的輸出流 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); //發(fā)送請求參數(shù)即數(shù)據(jù) out.write(data); //flush輸出流的緩沖 out.flush(); /** * 下面的代碼相當(dāng)于,獲取調(diào)用第三方http接口后返回的結(jié)果 */ //獲取URLConnection對象對應(yīng)的輸入流 InputStream is = conn.getInputStream(); //構(gòu)造一個字符流緩存 br = new BufferedReader(new InputStreamReader(is)); String str = ""; while ((str = br.readLine()) != null){ result += str; } System.out.println(result); //關(guān)閉流 is.close(); //斷開連接,disconnect是在底層tcp socket鏈接空閑時才切斷,如果正在被其他線程使用就不切斷。 conn.disconnect(); } catch (Exception e) { e.printStackTrace(); }finally { try { if (out != null){ out.close(); } if (br != null){ br.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { /** *手機(jī)信息查詢接口:http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=手機(jī)號 * http://api.showji.com/Locating/www.showji.com.aspx?m=手機(jī)號&output=json&callback=querycallback */ doPostOrGet("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", ""); } }
三、 通過apache common封裝好的HttpClient
(1)httpClient的get或post請求方式步驟
- 生成一個HttpClient對象并設(shè)置相應(yīng)的參數(shù);
- 生成一個GetMethod對象或PostMethod并設(shè)置響應(yīng)的參數(shù);
- 用HttpClient生成的對象來執(zhí)行GetMethod生成的Get方法;
- 處理響應(yīng)狀態(tài)碼;
- 若響應(yīng)正常,處理HTTP響應(yīng)內(nèi)容;
- 釋放連接。
(2)導(dǎo)入如下jar包
<!--HttpClient--> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
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; import java.io.InputStream; public class HttpClientToInterface { /** * httpClient的get請求方式 * 使用GetMethod來訪問一個URL對應(yīng)的網(wǎng)頁實(shí)現(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è)置請求重試處理,用的是默認(rèn)的重試處理:請求三次 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=utf-8"); //必須設(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) { doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "UTF-8"); JSONObject jsonObject = new JSONObject(); jsonObject.put("commentId", "13026194071"); doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject); } }
四、 通過Apache封裝好的CloseableHttpClient
CloseableHttpClient是在HttpClient的基礎(chǔ)上修改更新而來的,這里還涉及到請求頭token的設(shè)置(請求驗(yàn)證),利用fastjson轉(zhuǎn)換請求或返回結(jié)果字符串為json格式,當(dāng)然上面兩種方式也是可以設(shè)置請求頭token、json的,這里只在下面說明
(1)maven
<!--CloseableHttpClient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency>
import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class CloseableHttpClientToInterface { private static String tokenString = ""; private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED"; private static CloseableHttpClient httpClient = null; /** * 以get方式調(diào)用第三方接口 * @param url * @return */ public static String doGet(String url, String token){ //創(chuàng)建HttpClient對象 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); try { if (tokenString != null && !tokenString.equals("")){ tokenString = getToken(); } //api_gateway_auth_token自定義header頭,用于token驗(yàn)證使用 get.addHeader("api_gateway_auth_token", tokenString); get.addHeader("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"); HttpResponse response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //返回json格式 String res = EntityUtils.toString(response.getEntity()); return res; } } catch (IOException e) { e.printStackTrace(); } return null; } /** * 以post方式調(diào)用第三方接口 * @param url * @param json * @return */ public static String doPost(String url, JSONObject json){ try { if (httpClient == null){ httpClient = HttpClientBuilder.create().build(); } HttpPost post = new HttpPost(url); if (tokenString != null && !tokenString.equals("")){ tokenString = getToken(); } //api_gateway_auth_token自定義header頭,用于token驗(yàn)證使用 post.addHeader("api_gateway_auth_token", tokenString); post.addHeader("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"); StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); //發(fā)送json數(shù)據(jù)需要設(shè)置contentType s.setContentType("application/x-www-form-urlencoded"); //設(shè)置請求參數(shù) post.setEntity(s); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //返回json格式 String res = EntityUtils.toString(response.getEntity()); return res; } } catch (Exception e) { e.printStackTrace(); }finally { if (httpClient != null){ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } /** * 獲取第三方接口的token */ public static String getToken(){ String token = ""; JSONObject object = new JSONObject(); object.put("appid", "appid"); object.put("secretkey", "secretkey"); try { if (httpClient == null){ httpClient = HttpClientBuilder.create().build(); } HttpPost post = new HttpPost("http://localhost/login"); post.addHeader("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"); StringEntity s = new StringEntity(object.toString()); s.setContentEncoding("UTF-8"); //發(fā)送json數(shù)據(jù)需要設(shè)置contentType s.setContentType("application/x-www-form-urlencoded"); //設(shè)置請求參數(shù) post.setEntity(s); HttpResponse response = httpClient.execute(post); //這里可以把返回的結(jié)果按照自定義的返回數(shù)據(jù)結(jié)果,把string轉(zhuǎn)換成自定義類 //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class); //把response轉(zhuǎn)為jsonObject JSONObject result = JSONObject.parseObject(response); if (result.containsKey("token")){ token = result.getString("token"); } } catch (Exception e) { e.printStackTrace(); } return token; } /** * 測試 */ public static void test(String telephone){ JSONObject object = new JSONObject(); object.put("telephone", telephone); try { //首先獲取token tokenString = getToken(); String response = doPost("http://localhost/searchUrl", object); //如果返回的結(jié)果是list形式的,需要使用JSONObject.parseArray轉(zhuǎn)換 //List<Result> list = JSONObject.parseArray(response, Result.class); System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { test("12345678910"); } }
/** * 執(zhí)行一個HTTP POST請求,返回請求響應(yīng)的HTML * @param url * 請求的URL地址 * @param params * 請求的查詢參數(shù),可以為null * @return 返回請求響應(yīng)的HTML */ public static void doPost(String url, String name, String pwd, String phone, String content) { // 創(chuàng)建默認(rèn)的httpClient實(shí)例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 創(chuàng)建httppost HttpPost httppost = new HttpPost(url); // 創(chuàng)建參數(shù)隊(duì)列 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("account", name)); formparams.add(new BasicNameValuePair("passwd", pwd)); formparams.add(new BasicNameValuePair("phone", phone)); formparams.add(new BasicNameValuePair("content", content)); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); } } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } finally { // 關(guān)閉連接,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
總結(jié)
到此這篇關(guān)于Java調(diào)用第三方http接口的四種方式的文章就介紹到這了,更多相關(guān)Java調(diào)用第三方http接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java如何基于okhttp請求SSE接口流式返回詳解
- Java請求Http接口OkHttp超詳細(xì)講解(附帶工具類)
- java+Okhttp3調(diào)用接口的實(shí)例
- Java中的HttpServletRequest接口詳細(xì)解讀
- Java調(diào)用HTTPS接口實(shí)現(xiàn)繞過SSL認(rèn)證
- Java發(fā)送http請求調(diào)用第三方接口獲取token方式
- Java調(diào)用第三方http接口的常用方式總結(jié)
- Java實(shí)現(xiàn)調(diào)用對方http接口得到返回數(shù)據(jù)
- Java 調(diào)用 HTTP 接口的 7 種方式示例代碼(全網(wǎng)最全指南)
相關(guān)文章
java學(xué)習(xí)筆記之eclipse+tomcat 配置
俗話說:工欲善其事必先利其器,既然要學(xué)習(xí)java,首先把java的開發(fā)環(huán)境搗鼓一下吧,這里我們來談?wù)別clipse+tomcat的配置方法。2014-11-11SpringBoot整合Security實(shí)現(xiàn)權(quán)限控制框架(案例詳解)
Spring Security是一個能夠?yàn)榛赟pring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框,是一個重量級的安全管理框架,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-08-08SpringBoot中使用MyBatis-Plus詳細(xì)步驟
MyBatis-Plus是MyBatis的增強(qiáng)工具,簡化了MyBatis的使用,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2025-01-01Spring AOP實(shí)現(xiàn)復(fù)雜的日志記錄操作(自定義注解)
Spring AOP實(shí)現(xiàn)復(fù)雜的日志記錄操作(自定義注解),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09Java之while與do-while循環(huán)的用法詳解
在上一篇文章中,給大家講解了循環(huán)的概念,并重點(diǎn)給大家講解了for循環(huán)的使用。但在Java中,除了for循環(huán)之外,還有while、do-while、foreach等循環(huán)形式。這篇文章給大家講解while循環(huán)的使用2023-05-05SpringBoot中的配置類(@Configuration)
這篇文章主要介紹了SpringBoot中的配置類(@Configuration),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06