SpringBoot 接口開發教程(httpclient客戶端)

SpringBoot接口開發

服務端

@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");//發送json數據需要設置contentType
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
					/*讀返回數據*/
                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 += "發送成功";
                }else{
                    strResult += "發送失敗,"+code;
                }
 
            } else {
                String err = response.getStatusLine().getStatusCode()+"";
                strResult += "發送失敗:"+err;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return strResult;
    }

get請求

/**
     * 發送 get請求
     */
    public void get() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 創建httpget.
            HttpGet httpget = new HttpGet("http://127.0.0.1:8088/landary/showuser");
            System.out.println("executing request " + httpget.getURI());
            // 執行get請求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 獲取響應實體
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印響應狀態
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印響應內容長度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印響應內容
                    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 {
            // 關閉連接,釋放資源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

SpringBoot之httpclient使用

超文本傳輸協議(HTTP,HyperText Transfer Protocol)是互聯網上應用最為廣泛的一種網絡協議。所有的WWW文件都必須遵守這個標準。而HttpClient是可以支持http相關協議的工具包

它有如下功能:

1.實現瞭所有的http方法(GET,POST,PUT,HEAD 等)

2.支持自動轉向

3.支持 HTTPS 協議

4.支持代理服務器等

既然HttpClient使用這麼廣泛,則本文講解下Spring Boot 中怎麼使用HttpClient.如下:

引入相關依賴

       <!-- 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所需包 -->
         <!-- 數據解析所需包 -->   
        <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>
        <!-- /數據解析所需包 -->   

編寫相關工具類

寫個http的工具類,以便業務代碼直接調用,如下:

/**
 * Http工具類
 */
public class HttpUtils {
    /**
     * 發送POST請求
     * @param url 請求url
     * @param data 請求數據
     * @return 結果
     */
    @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);
        }
        // 設置回調接口接收的消息頭
        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參數中的鍵值對
     * @param url url參數
     * @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;
    }
}

業務代碼中使用

業務中代碼使用,拼裝請求Url和請求數據,就可以調用工具類裡的doPost()方法開始直接使用咯。如下:

private String getFileStorePath(String courtId, String seesionId){
        String fileStorePath = StringUtils.EMPTY;
        //請求參數
        String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}";
        String fileServiceUrl="http://111.11.11.11:8086";
        //發送請求,獲取結果
        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;
    }

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: