最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

實(shí)例詳解Java調(diào)用第三方接口方法

 更新時(shí)間:2022年06月15日 12:06:46   作者:胡蘿卜★  
很多項(xiàng)目都會(huì)封裝規(guī)定好本身項(xiàng)目的接口規(guī)范,所以大多數(shù)需要去調(diào)用對(duì)方提供的接口或第三方接口(短信、天氣等),下面這篇文章主要給大家介紹了關(guān)于Java調(diào)用第三方接口方法的相關(guān)資料,需要的朋友可以參考下

一、 通過(guò)JDK網(wǎng)絡(luò)類Java.net.HttpURLConnection

1.java.net包下的原生java api提供的http請(qǐng)求

使用步驟:

1、通過(guò)統(tǒng)一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection)。

2、設(shè)置請(qǐng)求的參數(shù)。

3、發(fā)送請(qǐng)求。

4、以輸入流的形式獲取返回內(nèi)容。

5、關(guān)閉輸入流。

2.HttpClientUtil工具類

/**
 * jdk 調(diào)用第三方接口
 * @author hsq
 */
public class HttpClientUtil2 {


    /**
     * 以post方式調(diào)用對(duì)方接口方法
     * @param pathUrl
     */
    public static String doPost(String pathUrl, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);

            //打開(kāi)和url之間的連接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //設(shè)定請(qǐng)求的方法為"POST",默認(rèn)是GET
            //post與get的不同之處在于post的參數(shù)不是放在URL字串里面,而是放在http請(qǐng)求的正文內(nèi)。
            conn.setRequestMethod("POST");

            //設(shè)置30秒連接超時(shí)
            conn.setConnectTimeout(30000);
            //設(shè)置30秒讀取超時(shí)
            conn.setReadTimeout(30000);

            // 設(shè)置是否向httpUrlConnection輸出,因?yàn)檫@個(gè)是post請(qǐng)求,參數(shù)要放在http正文內(nèi),因此需要設(shè)為true, 默認(rèn)情況下是false;
            conn.setDoOutput(true);
            // 設(shè)置是否從httpUrlConnection讀入,默認(rèn)情況下是true;
            conn.setDoInput(true);

            // Post請(qǐng)求不能使用緩存
            conn.setUseCaches(false);

            //設(shè)置通用的請(qǐng)求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //維持長(zhǎng)鏈接
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //連接,從上述url.openConnection()至此的配置必須要在connect之前完成,
            conn.connect();

            /**
             * 下面的三句代碼,就是調(diào)用第三方http接口
             */
            //獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流
            //此處getOutputStream會(huì)隱含的進(jìn)行connect(即:如同調(diào)用上面的connect()方法,所以在開(kāi)發(fā)中不調(diào)用上述的connect()也可以)。
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //發(fā)送請(qǐng)求參數(shù)即數(shù)據(jù)
            out.write(data);
            //flush輸出流的緩沖
            out.flush();

            /**
             * 下面的代碼相當(dāng)于,獲取調(diào)用第三方http接口后返回的結(jié)果
             */
            //獲取URLConnection對(duì)象對(duì)應(yīng)的輸入流
            InputStream is = conn.getInputStream();
            //構(gòu)造一個(gè)字符流緩存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);
            //關(guān)閉流
            is.close();
            //斷開(kāi)連接,disconnect是在底層tcp socket鏈接空閑時(shí)才切斷,如果正在被其他線程使用就不切斷。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 以get方式調(diào)用對(duì)方接口方法
     * @param pathUrl
     */
    public static String doGet(String pathUrl){
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);

            //打開(kāi)和url之間的連接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //設(shè)定請(qǐng)求的方法為"GET",默認(rèn)是GET
            //post與get的不同之處在于post的參數(shù)不是放在URL字串里面,而是放在http請(qǐng)求的正文內(nèi)。
            conn.setRequestMethod("GET");

            //設(shè)置30秒連接超時(shí)
            conn.setConnectTimeout(30000);
            //設(shè)置30秒讀取超時(shí)
            conn.setReadTimeout(30000);

            // 設(shè)置是否向httpUrlConnection輸出,因?yàn)檫@個(gè)是post請(qǐng)求,參數(shù)要放在http正文內(nèi),因此需要設(shè)為true, 默認(rèn)情況下是false;
            conn.setDoOutput(true);
            // 設(shè)置是否從httpUrlConnection讀入,默認(rèn)情況下是true;
            conn.setDoInput(true);

            // Post請(qǐng)求不能使用緩存(get可以不使用)
            conn.setUseCaches(false);

            //設(shè)置通用的請(qǐng)求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //維持長(zhǎng)鏈接
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            //連接,從上述url.openConnection()至此的配置必須要在connect之前完成,
            conn.connect();

            /**
             * 下面的代碼相當(dāng)于,獲取調(diào)用第三方http接口后返回的結(jié)果
             */
            //獲取URLConnection對(duì)象對(duì)應(yīng)的輸入流
            InputStream is = conn.getInputStream();
            //構(gòu)造一個(gè)字符流緩存
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);
            //關(guān)閉流
            is.close();
            //斷開(kāi)連接,disconnect是在底層tcp socket鏈接空閑時(shí)才切斷,如果正在被其他線程使用就不切斷。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

3.第三方api接口

/**
 * @author hsq
 */
@RestController
@RequestMapping("/api")
public class HelloWorld {

    private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);

    @GetMapping ("/getHello")
    public Result getHelloWord(){
        log.info("進(jìn)入到api接口.......");
        return Result.success("hello world api get 接口數(shù)據(jù)");
    }

    @PostMapping("/postHello")
    public Result postHelloWord(@RequestBody User user){
        log.info("進(jìn)入post 方法.....");
        System.out.println(user.toString());
        return Result.success("hello world api post接口數(shù)據(jù)");
    }
}

4.測(cè)試類

 @Test
    public void testJDKApi(){
        //測(cè)試get方法
        String s = HttpClientUtil2.doGet("http://localhost:9092/api/getHello");
        System.out.println("get方法:"+s);
        //測(cè)試post方法
        User user = new User();
        user.setUname("胡蘿卜");
        user.setRole("普通用戶");
        //把對(duì)象轉(zhuǎn)換為json格式
        String s1 = JsonUtil.toJson(user);
        String postString = HttpClientUtil2.doPost("http://localhost:9092/api/postHello",s1);
        System.out.println("post方法:"+postString);
    }

結(jié)果:

二、通過(guò)Apache common封裝好的HttpClient

1.引入依賴

 		<!--HttpClient-->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

2.httpClientUtil

/**
	*httpClient的get請(qǐng)求方式
     * 使用GetMethod來(lái)訪問(wèn)一個(gè)URL對(duì)應(yīng)的網(wǎng)頁(yè)實(shí)現(xiàn)步驟:
     * 1.生成一個(gè)HttpClient對(duì)象并設(shè)置相應(yīng)的參數(shù);
     * 2.生成一個(gè)GetMethod對(duì)象并設(shè)置響應(yīng)的參數(shù);
     * 3.用HttpClient生成的對(duì)象來(lái)執(zhí)行GetMethod生成的Get方法;
     * 4.處理響應(yīng)狀態(tài)碼;
     * 5.若響應(yīng)正常,處理HTTP響應(yīng)內(nèi)容;
     * 6.釋放連接。
 * @author hsq
 */
public class HttpClientUtil {

    /**
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset){
        /**
         * 1.生成HttpClient對(duì)象并設(shè)置參數(shù)
         */
        HttpClient httpClient = new HttpClient();
        //設(shè)置Http連接超時(shí)為5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        /**
         * 2.生成GetMethod對(duì)象并設(shè)置參數(shù)
         */
        GetMethod getMethod = new GetMethod(url);
        //設(shè)置get請(qǐng)求超時(shí)為5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //設(shè)置請(qǐng)求重試處理,用的是默認(rèn)的重試處理:請(qǐng)求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

        String response = "";

        /**
         * 3.執(zhí)行HTTP GET 請(qǐng)求
         */
        try {
            int statusCode = httpClient.executeMethod(getMethod);

            /**
             * 4.判斷訪問(wèn)的狀態(tài)碼
             */
            if (statusCode != HttpStatus.SC_OK){
                System.err.println("請(qǐng)求出錯(cuò):" + getMethod.getStatusLine());
            }

            /**
             * 5.處理HTTP響應(yīng)內(nèi)容
             */
            //HTTP響應(yīng)頭部信息,這里簡(jiǎn)單打印
            Header[] headers = getMethod.getResponseHeaders();
            for (Header h: headers){
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //讀取HTTP響應(yīng)內(nèi)容,這里簡(jiǎn)單打印網(wǎng)頁(yè)內(nèi)容
            //讀取為字節(jié)數(shù)組
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //讀取為InputStream,在網(wǎng)頁(yè)內(nèi)容數(shù)據(jù)量大時(shí)候推薦使用
            //InputStream response = getMethod.getResponseBodyAsStream();

        } catch (HttpException e) {
            //發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問(wèn)題
            System.out.println("請(qǐng)檢查輸入的URL!");
            e.printStackTrace();
        } catch (IOException e){
            //發(fā)生網(wǎng)絡(luò)異常
            System.out.println("發(fā)生網(wǎng)絡(luò)異常!");
        }finally {
            /**
             * 6.釋放連接
             */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post請(qǐng)求
     * @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è)置下面這個(gè)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");
        //添加請(qǐng)求參數(shù)
        //postMethod.addParameter("param", json.getString("param"));
        StringRequestEntity param = new StringRequestEntity(json.getString("param"));
        postMethod.setRequestEntity(param);
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                byte[] responseBody = postMethod.getResponseBody();
                res = new String(responseBody, "UTF-8");
                //res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}

3.第三方api接口

@RestController
@RequestMapping("/api")
public class HelloWorld {

    private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);


    @GetMapping ("/getHello")
    public Result getHelloWord(){
        log.info("進(jìn)入到api接口.......");
        return Result.success("hello world api get 接口數(shù)據(jù)");
    }

    @PostMapping("/postHello")
    public Result postHelloWord(@RequestBody User user){
        log.info("進(jìn)入post 方法.....");
        System.out.println(user.toString());
        return Result.success("hello world api post接口數(shù)據(jù)");
    }

}

4.測(cè)試類

 	@Test
    public void testApi() {
        //測(cè)試get方法
        String s = HttpClientUtil.doGet("http://localhost:9092/api/getHello", "UTF-8");
        System.out.println("get方法:"+s);
        //測(cè)試post方法
        User user = new User();
        user.setUname("胡蘿卜");
        user.setRole("普通用戶");
        JSONObject jsonObject = new JSONObject();
        String s1 = JsonUtil.toJson(user);
        jsonObject.put("param",s1);
        String postString = HttpClientUtil.doPost("http://localhost:9092/api/postHello", jsonObject);
        System.out.println("post方法:"+postString);
    }

結(jié)果:

三、通過(guò)Spring的RestTemplate

1.引入依賴

導(dǎo)入springboot的web包

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.RestTemplate配置類

/**
 * @author hsq
 */
@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;
    }
}

3.RestTemplate實(shí)現(xiàn)類

/**
 * @author hsq
 */
@Component
public class RestTemplateToInterface {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 以get方式請(qǐng)求第三方http接口 getForEntity
     * @param url
     * @return
     */
    public Result doGetWith1(String url){
        ResponseEntity<Result> responseEntity = restTemplate.getForEntity(url, Result.class);
        Result result = responseEntity.getBody();
        return result;
    }

    /**
     * 以get方式請(qǐng)求第三方http接口 getForObject
     * 返回值返回的是響應(yīng)體,省去了我們?cè)偃etBody()
     * @param url
     * @return
     */
    public Result doGetWith2(String url){
        Result result  = restTemplate.getForObject(url, Result.class);
        return result;
    }

    /**
     * 以post方式請(qǐng)求第三方http接口 postForEntity
     * @param url
     * @param user
     * @return
     */
    public String doPostWith1(String url,User user){
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
        String body = responseEntity.getBody();
        return body;
    }

    /**
     * 以post方式請(qǐng)求第三方http接口 postForEntity
     * 返回值返回的是響應(yīng)體,省去了我們?cè)偃etBody()
     * @param url
     * @param user
     * @return
     */
    public String doPostWith2(String url,User user){
        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;
    }
}

4.第三方api接口

/**
 * @author hsq
 */
@RestController
@RequestMapping("/api")
public class HelloWorld {

    private static final Logger log= LoggerFactory.getLogger(HelloWorld.class);

    @GetMapping ("/getHello")
    public Result getHelloWord(){
        log.info("進(jìn)入到api接口.......");
        return Result.success("hello world api get 接口數(shù)據(jù)");
    }

    @PostMapping("/postHello")
    public Result postHelloWord(@RequestBody User user){
        log.info("進(jìn)入post 方法.....");
        System.out.println(user.toString());
        return Result.success("hello world api post接口數(shù)據(jù)");
    }
}

5.測(cè)試類

//注入使用
@Autowired
private RestTemplateToInterface restTemplateToInterface;

@Test
public void testSpringBootApi(){
    Result result= restTemplateToInterface.doGetWith1("http://localhost:9092/api/getHello");
    System.out.println("get結(jié)果:"+result);
    User user = new User();
    user.setUname("胡蘿卜");
    user.setRole("普通用戶");
    String s = restTemplateToInterface.doPostWith1("http://localhost:9092/api/postHello", user);
    System.out.println("post結(jié)果:"+s);
}

結(jié)果:

總結(jié) 

到此這篇關(guān)于Java調(diào)用第三方接口方法的文章就介紹到這了,更多相關(guān)Java調(diào)用第三方接口方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java?SpringBoot項(xiàng)目如何優(yōu)雅的實(shí)現(xiàn)操作日志記錄

    Java?SpringBoot項(xiàng)目如何優(yōu)雅的實(shí)現(xiàn)操作日志記錄

    這篇文章主要介紹了Java?SpringBoot項(xiàng)目如何優(yōu)雅的實(shí)現(xiàn)操作日志記錄,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下
    2022-08-08
  • Java集合ArrayDeque類實(shí)例分析

    Java集合ArrayDeque類實(shí)例分析

    這篇文章主要介紹了Java集合ArrayDeque類實(shí)例分析的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • 我賭你不清楚Spring中關(guān)于Null的這些事

    我賭你不清楚Spring中關(guān)于Null的這些事

    這篇文章主要介紹了我賭你不清楚Spring中關(guān)于Null的這些事,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • SpringBoot用JdbcTemplates訪問(wèn)Mysql實(shí)例代碼

    SpringBoot用JdbcTemplates訪問(wèn)Mysql實(shí)例代碼

    本篇文章主要介紹了SpringBoot用JdbcTemplates訪問(wèn)Mysql實(shí)例代碼,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2017-05-05
  • java中通用的線程池實(shí)例代碼

    java中通用的線程池實(shí)例代碼

    java中通用的線程池實(shí)例代碼,需要的朋友可以參考一下
    2013-03-03
  • spring注解 @Valid 的作用說(shuō)明

    spring注解 @Valid 的作用說(shuō)明

    這篇文章主要介紹了spring注解 @Valid 的作用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 基于Gradle搭建Spring?5.3.13-release源碼閱讀環(huán)境的詳細(xì)流程

    基于Gradle搭建Spring?5.3.13-release源碼閱讀環(huán)境的詳細(xì)流程

    這篇文章主要介紹了基于Gradle搭建Spring?5.3.13-release源碼閱讀環(huán)境,首先安裝jdk、gradle等一系列必要操作,本文通過(guò)實(shí)例代碼相結(jié)合給大家講解的非常詳細(xì),需要的朋友可以參考下
    2022-04-04
  • Java中的ReentrantLock使用解析

    Java中的ReentrantLock使用解析

    這篇文章主要介紹了Java中的ReentrantLock使用解析,ReentrandLock即可重入鎖,可重入鎖解決的是重入鎖定的問(wèn)題,重入鎖定指的是當(dāng)一個(gè)線程執(zhí)行邏輯時(shí),需要兩次獲取鎖,而該鎖不可重入就會(huì)導(dǎo)致內(nèi)部嵌套無(wú)法獲取鎖導(dǎo)致Reentrance Lockout發(fā)生,需要的朋友可以參考下
    2023-11-11
  • 解決引入Redisson可能會(huì)出現(xiàn)項(xiàng)目啟動(dòng)失敗的問(wèn)題

    解決引入Redisson可能會(huì)出現(xiàn)項(xiàng)目啟動(dòng)失敗的問(wèn)題

    這篇文章主要介紹了解決引入Redisson可能會(huì)出現(xiàn)項(xiàng)目啟動(dòng)失敗的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • Java異常處理實(shí)例分析

    Java異常處理實(shí)例分析

    這篇文章主要介紹了Java異常處理,實(shí)例分析了java異常處理的常見(jiàn)用法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-04-04

最新評(píng)論

雷州市| 武隆县| 峨山| 五峰| 苍溪县| 阿克| 成都市| 华池县| 东丰县| 灌南县| 当阳市| 绥宁县| 永定县| 兴业县| 高州市| 闽清县| 息烽县| 绥宁县| 京山县| 阜新市| 繁峙县| 黄平县| 武冈市| 福州市| 油尖旺区| 平泉县| 神木县| 普定县| 利辛县| 荃湾区| 平果县| 穆棱市| 错那县| 东安县| 娄烦县| 东方市| 青河县| 巴东县| 宜兰市| 万年县| 宁陕县|