欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)調(diào)用對方http接口得到返回數(shù)據(jù)

 更新時間:2021年09月16日 10:22:34   作者:peachlf  
這篇文章主要介紹了Java實現(xiàn)調(diào)用對方http接口得到返回數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Java 用對方http接口得到返回數(shù)據(jù)

如圖所示我們這里自己寫一個接口作為訪問地址,返回的是json字符串

首先我們在瀏覽器訪問這個接口的地址,會在瀏覽器打印出如圖所示的內(nèi)容,

然后我們寫一個方法訪問剛剛的接口地址,使用HttpURLConnextion進(jìn)行訪問,通過BufferedReader獲取流,已得到返回的值

運行這個方法,會在控制臺打印出接口返回的值,也可以進(jìn)行相應(yīng)的操作

如圖所示是第二種方法,通過URL進(jìn)行連接,然后通過openStream方法獲取返回值的流轉(zhuǎn)為BufferedReader,然后進(jìn)行相應(yīng)的操作

接著賦值url接口地址后,運行后結(jié)果如圖所示,這里還可以使用jsonfrom等方法對獲取的返回值進(jìn)行json解析,以更方便操作

java后臺工具類調(diào)用api接口,解析數(shù)據(jù)

httpclient后臺調(diào)用接口,解析數(shù)據(jù)

一 、 引入jar包

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
         <!-- JSON轉(zhuǎn)換包 -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

二、 httpclient請求接口工具類

2.1 get、post、“head”, “options”, “delete”, "trace"等方式

public class HttpClient {
    /**
     * 向目的URL發(fā)送post請求
     *
     * @param url          目的url
     * @param headerParams 請求頭參數(shù) key:value
     * @param bodyParams   請求體參數(shù)  key:value
     * @return 
     */
    public static String sendPostRequest(String url, Map<String, String> headerParams,
                                         Map<String, String> bodyParams) {
        RestTemplate client = new RestTemplate();
        //新建Http頭,add方法可以添加參數(shù)
        HttpHeaders headers = new HttpHeaders();
        //給請求頭設(shè)置參數(shù)
        for (String key : headerParams.keySet()) {
            headers.add(key, headerParams.get(key));
        }
        //設(shè)置請求發(fā)送方式HttpMethod.GET、HttpMethod.DELETE等
        HttpMethod method = HttpMethod.POST;
        // 設(shè)置提交方式這里設(shè)置成application/json格式
        headers.setContentType(MediaType.APPLICATION_JSON);
        //將請求頭部和參數(shù)合成一個請求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);
        //執(zhí)行HTTP請求,將返回的結(jié)構(gòu)使用String 類格式化(可設(shè)置為對應(yīng)返回值格式的類)
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        //返回類型也可以自動填充到實體類當(dāng)中去,比如我自己創(chuàng)建了User類,當(dāng)然字段名稱要和返回字段一致
        //ResponseEntity<User> response = client.exchange(url, method, requestEntity, User.class);
        return response.getBody();
    }

2.2 PATCH等其他方式

/**
     * 向目的URL發(fā)送patch請求,只比其他方式多了一個允許aptch方式的方法。
     * 由于httpclient不支持patch請求,所以需要反射方式獲取連接對象,增加patch方式
     * @param url          目的url
     * @param headerParams 請求頭參數(shù)
     * @param bodyParams   請求體參數(shù)
     * @return AdToutiaoJsonTokenData
     */
    public static String sendPatchRequest(String url, Map<String, String> headerParams,
                                          Map<String, String> bodyParams) {
        //httpclient不支持patch請求,反射方式獲取連接對象,增加patch方式
        allowMethods("PATCH");
        RestTemplate client = new RestTemplate();
        //新建Http頭,add方法可以添加參數(shù)
        HttpHeaders headers = new HttpHeaders();
        //給請求頭設(shè)置參數(shù)
        for (String key : headerParams.keySet()) {
            headers.add(key, headerParams.get(key));
        }
        //headers.add("X-HTTP-Method-Override", "PATCH");
        //設(shè)置請求發(fā)送方式
        HttpMethod method = HttpMethod.PATCH;
        // 設(shè)置提交方式這里設(shè)置成application/json格式
        headers.setContentType(MediaType.APPLICATION_JSON);
        //將請求頭部和參數(shù)合成一個請求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);
        //執(zhí)行HTTP請求,將返回的結(jié)構(gòu)使用String 類格式化(可設(shè)置為對應(yīng)返回值格式的類)
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }
    //增加支持patch請求方式
    private static void allowMethods(String... methods) {
        try {
         //獲取連接類的屬性,給屬性添加aptch就允許aptch請求方式了 
            Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
            methodsField.setAccessible(true);
            String[] oldMethods = (String[]) methodsField.get(null);
            Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
            methodsSet.addAll(Arrays.asList(methods));
            String[] newMethods = methodsSet.toArray(new String[0]);
            methodsField.set(null/*static field*/, newMethods);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

2.3 解析數(shù)據(jù)

//工具類調(diào)用api接口,獲取返回數(shù)據(jù)
 String result = HttpClient.sendPostRequest(createZoomMeetingUrl,header,body);
        JSONObject json = JSONObject.fromObject(result);
        //解析獲取數(shù)據(jù)
        String startUrl = json.getString("start_url");
        String joinUrl = json.getString("join_url");
        //會議室id
        int id = json.getInt("id");
        //解析數(shù)據(jù)數(shù)據(jù)
        JSONArray jsonArray = json.getJSONArray("users");
        for(int i=0;i<jsonArray .size();i++){
          String firstName = jsonArray.getJSONObject(i).getString("first_name");
          ...............
        }

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論