關於接口調用的方法和理解

此接口調用主要是針對於JSON格式的傳參,http協議的通訊(此方法講解的是POST訪問方式),以下是對接口調用的一些理解 ,以便後續學習,如下分爲2個部分:1、調用的主方法; 2、封裝的工具類首先,調用的主要方法由於接口地址URL是通過構造方法進行賦值,在方法中就不需要傳參了,調用主要方法中需傳入接口所需參數,並轉換成JSON格式的字符串,再傳入到工具類進行處理調用(工具類往下翻)
    public String test(String a, String b) throws Exception {
        String url ="地址";
    	Map<String, String> params = new HashMap<>();
        Map<String, Map<String, String>> requestMap = new HashMap<>();
        params.put("a", a);
        params.put("b", b);
        requestMap.put("Request", params);
        
        HttpPost httpPost = null;
        try {
        	String json = JsonUtil.writeValueAsString(requestMap);
        	httpPost = HttpRequest.getHttpPost(url, json);
            
            return HttpRequest.getHttpPostRequest(httpPost);
        } catch (Throwable e) {
            throw new Exception();
        } 

    }


其次,工具類

工具類一,此工具類需要傳入接口地址和接口所需要的參數,並設置傳輸格式、字符集,並將參數與URL地址組合,返回一個HttpPost的請求方式:

public static HttpPost getHttpPost(String url,String json){
    	StringEntity requestEntity = new StringEntity(json, Charset.forName("utf-8"));
    	requestEntity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
    	httpPost.setEntity(requestEntity);
    	httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    	return httpPost;
    }


工具類二,此工具類是針對上面返回HttpPost進行處理,傳入HttpPost ,並創建CloseableHttpClient httpclient對象,

httpclient 進行execute(httpPost)方法,傳入httpPost進行調用訪問
 :

public static String getHttpPostRequest(HttpPost httpPost) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //請求超時設置
    RequestConfig requestConfig = RequestConfig.custom()
    .setConnectTimeout(30*1000)
    .setConnectionRequestTimeout(30*1000)
    .setSocketTimeout(30*1000)
    .build();
    httpPost.setConfig(requestConfig);


    CloseableHttpResponse response = null;
    StatusLine status = null;
    int statuscode = 0;
        try {
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            
            if (entity != null) {
            String msg = new String(EntityUtils.toString(entity, "utf-8"));
                return msg;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
        status = response.getStatusLine();
        statuscode = status.getStatusCode();
    if (statuscode != HttpStatus.SC_OK) { //狀態碼200表示連接成功
    if(httpPost != null)
    httpPost.abort();
}
        }
        return "";
    }


發佈了22 篇原創文章 · 獲贊 35 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章