SpringBoot 接口開發(fā)教程(httpclient客戶端)
SpringBoot接口開發(fā)
服務(wù)端
@RestController @RequestMapping("/landary") public class landaryController { @RequestMapping("adduser") public JSONObject addUser(@RequestBody JSONObject userEntity) { System.out.println(JSONObject.toJSONString(userEntity)); JSONObject json=new JSONObject(); json.fluentPut("code","500").fluentPut("result",userEntity); return json; } @RequestMapping("showuser") public Object showUser() { return JSON.toJSONString("hhh"); } }
客戶端post請求
public static String sendSms(String uid,String title,String content){ HttpClient httpclient = new DefaultHttpClient(); String smsUrl="http://127.0.0.1:8088/landary/adduser"; HttpPost httppost = new HttpPost(smsUrl); String strResult = ""; try { JSONObject jobj = new JSONObject(); jobj.put("uid", uid); jobj.put("title", title); jobj.put("content",content); System.out.println(jobj.toString()); // nameValuePairs.add(new BasicNameValuePair("msg", (jobj.toString()))); /* httppost.addHeader("Content-type", "application/json; charset=utf-8"); httppost.setHeader("Accept", "application/json"); httppost.setEntity(new StringEntity(jobj.toString(), Charset.forName("UTF-8")));*/ StringEntity s = new StringEntity(jobj.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//發(fā)送json數(shù)據(jù)需要設(shè)置contentType httppost.setEntity(s); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { /*讀返回?cái)?shù)據(jù)*/ String conResult = EntityUtils.toString(response .getEntity()); System.out.println(conResult); JSONObject sobj = new JSONObject(); sobj = JSONObject.parseObject(conResult); String result = sobj.getString("result"); String code = sobj.getString("code"); if(code.equals("500")){ System.out.println(result); strResult += "發(fā)送成功"; }else{ strResult += "發(fā)送失敗,"+code; } } else { String err = response.getStatusLine().getStatusCode()+""; strResult += "發(fā)送失敗:"+err; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return strResult; }
get請求
/** * 發(fā)送 get請求 */ public void get() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 創(chuàng)建httpget. HttpGet httpget = new HttpGet("http://127.0.0.1:8088/landary/showuser"); System.out.println("executing request " + httpget.getURI()); // 執(zhí)行g(shù)et請求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 獲取響應(yīng)實(shí)體 HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); // 打印響應(yīng)狀態(tài) System.out.println(response.getStatusLine()); if (entity != null) { // 打印響應(yīng)內(nèi)容長度 System.out.println("Response content length: " + entity.getContentLength()); // 打印響應(yīng)內(nèi)容 System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關(guān)閉連接,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
SpringBoot之httpclient使用
超文本傳輸協(xié)議(HTTP,HyperText Transfer Protocol)是互聯(lián)網(wǎng)上應(yīng)用最為廣泛的一種網(wǎng)絡(luò)協(xié)議。所有的WWW文件都必須遵守這個標(biāo)準(zhǔn)。而HttpClient是可以支持http相關(guān)協(xié)議的工具包
它有如下功能:
1.實(shí)現(xiàn)了所有的http方法(GET,POST,PUT,HEAD 等)
2.支持自動轉(zhuǎn)向
3.支持 HTTPS 協(xié)議
4.支持代理服務(wù)器等
既然HttpClient使用這么廣泛,則本文講解下Spring Boot 中怎么使用HttpClient.如下:
引入相關(guān)依賴
? ? ? ?<!-- http所需包 --> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId> ? ? ? ? ? ? <artifactId>httpclient</artifactId> ? ? ? ? </dependency> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId> ? ? ? ? ? ? <artifactId>httpcore</artifactId> ? ? ? ? </dependency> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>org.apache.httpcomponents</groupId> ? ? ? ? ? ? <artifactId>httpmime</artifactId> ? ? ? ? </dependency> ? ? ? ? ?<!-- /http所需包 --> ? ? ? ? ?<!-- 數(shù)據(jù)解析所需包 --> ?? ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>org.apache.commons</groupId> ? ? ? ? ? ? <artifactId>commons-lang3</artifactId> ? ? ? ? ? ? <version>3.4</version> ? ? ? ? </dependency> ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>commons-lang</groupId> ? ? ? ? ? ? <artifactId>commons-lang</artifactId> ? ? ? ? ? ? <version>2.6</version> ? ? ? ? </dependency> ?? ? ? ? ? <dependency> ? ? ? ? ? ? <groupId>com.alibaba</groupId> ? ? ? ? ? ? <artifactId>fastjson</artifactId> ? ? ? ? ? ? <version>1.2.4</version> ? ? ? ? </dependency> ? ? ? ? <!-- /數(shù)據(jù)解析所需包 --> ??
編寫相關(guān)工具類
寫個http的工具類,以便業(yè)務(wù)代碼直接調(diào)用,如下:
/** ?* Http工具類 ?*/ public class HttpUtils { ? ? /** ? ? ?* 發(fā)送POST請求 ? ? ?* @param url 請求url ? ? ?* @param data 請求數(shù)據(jù) ? ? ?* @return 結(jié)果 ? ? ?*/ ? ? @SuppressWarnings("deprecation") ? ? public static String doPost(String url, String data) { ? ? ? ? CloseableHttpClient httpClient = HttpClients.createDefault(); ? ? ? ? HttpPost httpPost = new HttpPost(url); ? ? ? ? RequestConfig requestConfig = RequestConfig.custom() ? ? ? ? ? ? ? ? .setSocketTimeout(10000).setConnectTimeout(20000) ? ? ? ? ? ? ? ? .setConnectionRequestTimeout(10000).build(); ? ? ? ? httpPost.setConfig(requestConfig); ? ? ? ? String context = StringUtils.EMPTY; ? ? ? ? if (!StringUtils.isEmpty(data)) { ? ? ? ? ? ? StringEntity body = new StringEntity(data, "utf-8"); ? ? ? ? ? ? httpPost.setEntity(body); ? ? ? ? } ? ? ? ? // 設(shè)置回調(diào)接口接收的消息頭 ? ? ? ? httpPost.addHeader("Content-Type", "application/json"); ? ? ? ? CloseableHttpResponse response = null; ? ? ? ? try { ? ? ? ? ? ? response = httpClient.execute(httpPost); ? ? ? ? ? ? HttpEntity entity = response.getEntity(); ? ? ? ? ? ? context = EntityUtils.toString(entity, HTTP.UTF_8); ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.getStackTrace(); ? ? ? ? } finally { ? ? ? ? ? ? try { ? ? ? ? ? ? ? ? response.close(); ? ? ? ? ? ? ? ? httpPost.abort(); ? ? ? ? ? ? ? ? httpClient.close(); ? ? ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? ? ? e.getStackTrace(); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return context; ? ? } ? ? /** ? ? ?* 解析出url參數(shù)中的鍵值對 ? ? ?* @param url url參數(shù) ? ? ?* @return 鍵值對 ? ? ?*/ ? ? public static Map<String, String> getRequestParam(String url) { ? ? ? ? Map<String, String> map = new HashMap<String, String>(); ? ? ? ? String[] arrSplit = null; ? ? ? ? // 每個鍵值為一組 ? ? ? ? arrSplit = url.split("[&]"); ? ? ? ? for (String strSplit : arrSplit) { ? ? ? ? ? ? String[] arrSplitEqual = null; ? ? ? ? ? ? arrSplitEqual = strSplit.split("[=]"); ? ? ? ? ? ? // 解析出鍵值 ? ? ? ? ? ? if (arrSplitEqual.length > 1) { ? ? ? ? ? ? ? ? // 正確解析 ? ? ? ? ? ? ? ? map.put(arrSplitEqual[0], arrSplitEqual[1]); ? ? ? ? ? ? } else { ? ? ? ? ? ? ? ? if (arrSplitEqual[0] != "") { ? ? ? ? ? ? ? ? ? ? map.put(arrSplitEqual[0], ""); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return map; ? ? } }
業(yè)務(wù)代碼中使用
業(yè)務(wù)中代碼使用,拼裝請求Url和請求數(shù)據(jù),就可以調(diào)用工具類里的doPost()方法開始直接使用咯。如下:
private String getFileStorePath(String courtId, String seesionId){ ? ? ? ? String fileStorePath = StringUtils.EMPTY; ? ? ? ? //請求參數(shù) ? ? ? ? String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}"; ? ? ? ? String fileServiceUrl="http://111.11.11.11:8086"; ? ? ? ? //發(fā)送請求,獲取結(jié)果 ? ? ? ? String result = HttpUtils.doPost(fileServiceUrl + "/ms-service/voice/search", data); ? ? ? ? ? ? if(StringUtils.isNotBlank(result)){ ? ? ? ? ? ? com.alibaba.fastjson.JSONObject jsonobject = JSON.parseObject(result); ? ? ? ? ? ? fileStorePath = jsonobject.getString("path"); ? ? ? ? ? ? logger.info("fileStorePath = " + fileStorePath); ? ? ? ? } ? ? ? ? return fileStorePath; ? ? }
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)文件監(jiān)控器FileMonitor的實(shí)例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)文件監(jiān)控器FileMonitor的實(shí)例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12springboot集成mqtt的實(shí)踐開發(fā)
本篇文章主要介紹了springboot集成mqtt的實(shí)踐開發(fā),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08Java 基于Spire.Cloud.SDK for Java在PDF中繪制形狀
這篇文章主要介紹了Java 基于Spire.Cloud.SDK for Java在PDF中繪制形狀,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Java使用Collections工具類對List集合進(jìn)行排序
這篇文章主要介紹了Java使用Collections工具類對List集合進(jìn)行排序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10