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

java遠程調用接口、URL的方式代碼

 更新時間:2023年11月17日 10:48:23   作者:隨意石光  
我們都知道接口有自己本地的,也有遠程別人寫好的,而調用遠程接口的就需要使用遠程調用啦,這篇文章主要給大家介紹了關于java遠程調用接口、URL的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

一:httpUrlConnection

1.獲取HttpURLConnection連接對象

   /**
     * 獲取HttpURLConnection連接對象
     * @param url 遠程調用的url
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url){
        try {
            //建立連接
            URL httpUrl = new URL(url);
            HttpURLConnection urlConnection =(HttpURLConnection)httpUrl.openConnection();
            //向文件所在服務器發(fā)送標識信息,模擬瀏覽器
            urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");
            return urlConnection;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

2.遠程調用代碼

/**
     * 遠程調用登錄接口
     */
    public void accessLoginUrl(){
        //遠程調用接口的url
        String loginUrl = "http://localhost:8989/login/doLogin";
        OutputStream outputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            //獲取壓測接口的userTicket
            URL url = new URL(loginUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //登錄是post請求
            connection.setRequestMethod("POST");
            //post請求需要設置接口返回的數(shù)據(jù),所以設置為true
            connection.setDoOutput(true);
            //參數(shù)userId和密碼
            String param = "mobile=" + 13100000000000L + "&password=" + "123456";
            //獲取登錄接口返回的流文件
            outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            inputStream = connection.getInputStream();
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) >= 0){
                byteArrayOutputStream.write(buffer, 0, len);
            }
            //獲取響應結果
            String response = byteArrayOutputStream.toString();
            ObjectMapper objectMapper = new ObjectMapper();
            RespBean respBean = objectMapper.readValue(response, RespBean.class);
            String userTicket = (String) respBean.getObject();
            System.out.println("遠程調用接口的返回值"+userTicket);
            //userTicket就是遠程接口返回的值
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(byteArrayOutputStream != null){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

二:RestTemplate

2.1 什么是RestTemplate

  • 1.spring 框架提供的 RestTemplate 類可用于在應用中調用 rest 服務,它簡化了與 http 服務的通信方式,統(tǒng)一了 RESTful 的標準,封裝了 http 鏈接, 我們只需要傳入 url 及返回值類型即可。相較于之前常用的 HttpClient,RestTemplate 是一種更優(yōu)雅的調用 RESTful 服務的方式。

  • 2.在 Spring 應用程序中訪問第三方 REST 服務與使用 Spring RestTemplate 類有關。RestTemplate 類的設計原則與許多其他 Spring 模板類(例如 JdbcTemplate、JmsTemplate)相同,為執(zhí)行復雜任務提供了一種具有默認行為的簡化方法。

  • 3.RestTemplate 默認依賴 JDK 提供 http 連接的能力(HttpURLConnection),如果有需要的話也可以通過 setRequestFactory 方法替換為例如 Apache HttpComponents、Netty 或 OkHttp 等其它 HTTP library。

  • 4.考慮到 RestTemplate 類是為調用 REST 服務而設計的,因此它的主要方法與 REST 的基礎緊密相連就不足為奇了,后者是 HTTP 協(xié)議的方法:HEAD、GET、POST、PUT、DELETE 和 OPTIONS。例如,RestTemplate 類具有 headForHeaders()、getForObject()、postForObject()、put()和 delete()等方法。

2.2 配置RestTemplate

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        //解決401報錯時,報java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setErrorHandler(new RtErrorHandler());
        return restTemplate;
    }
    
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(15000);
        return factory;
    }

2.2 RestTemplate 添加請求頭headers和請求體body

        HttpHeaders header = new HttpHeaders();
        header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id");
        header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name");
        header.set("Authorization", "authorization");
        HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);
  • header 為需要設置的請求頭
  • AssetProcessVo為需要遠程調用接口傳遞的參數(shù)

2.3 示例代碼

/**
     * 遠程調用登錄接口
     */
    public void accessLoginUrl(){
        HttpHeaders header = new HttpHeaders();
        header.add("X-Consumer-Third-User-Id", "X-Consumer-Third-User-Id");
        header.add("X-Consumer-Third-User-Name", "X-Consumer-Third-User-Name");
        header.set("Authorization", "authorization");
        HttpEntity<AssetProcessVo> httpEntity = new HttpEntity<>(assetProcessVo, header);
        ResponseEntity<ByteArrayOutputStream> exchange;
        try {
            //保存案件名稱后,啟動工作流
            exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, ByteArrayOutputStream.class);
            if (exchange.getStatusCodeValue() == 200) {
                String response = byteArrayOutputStream.toString();
                ObjectMapper objectMapper = new ObjectMapper();
                RespBean respBean = objectMapper.readValue(response, RespBean.class);
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }

三:HttpClient

3.1 導入依賴

	<dependency>
	    <groupId>org.apache.httpcomponents</groupId>
	    <artifactId>httpclient</artifactId>
	    <version>4.5.3</version>
	</dependency>

3.2 使用方法

1,創(chuàng)建HttpClient對象;
2,指定請求URL,并創(chuàng)建請求對象,如果是get請求則創(chuàng)建HttpGet對象,post則創(chuàng)建HttpPost對象;
3,如果請求帶有參數(shù),對于get請求可直接在URL中加上參數(shù)請求,或者使用setParam(HetpParams params)方法設置參數(shù),對于HttpPost請求,可使用setParam(HetpParams params)方法或者調用setEntity(HttpEntity entity)方法設置參數(shù);
4,調用httpClient的execute(HttpUriRequest request)執(zhí)行請求,返回結果是一個response對象;
5,通過response的getHeaders(String name)或getAllHeaders()可獲得請求頭部信息,getEntity()方法獲取HttpEntity對象,該對象包裝了服務器的響應內容。

3.3 代碼實現(xiàn)

package com.cnzz.demo.remote.rpc;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
 
import java.io.IOException;
 
/**
 * ************************************************************
 * Copyright ? 2020 cnzz Inc.All rights reserved.  *    **
 * ************************************************************
 *
 * @program: demo
 * @description:
 * @author: cnzz
 * @create: 2020-12-23 17:41
 **/
 
public class HttpClientUtil {
 
    /**
     * httpClient的get請求方式
     * 使用GetMethod來訪問一個URL對應的網(wǎng)頁實現(xiàn)步驟:
     * 1.生成一個HttpClient對象并設置相應的參數(shù);
     * 2.生成一個GetMethod對象并設置響應的參數(shù);
     * 3.用HttpClient生成的對象來執(zhí)行GetMethod生成的Get方法;
     * 4.處理響應狀態(tài)碼;
     * 5.若響應正常,處理HTTP響應內容;
     * 6.釋放連接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1.生成HttpClient對象并設置參數(shù)
        HttpClient httpClient = new HttpClient();
        //設置Http連接超時為5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod對象并設置參數(shù)
        GetMethod getMethod = new GetMethod(url);
        //設置get請求超時為5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //設置請求重試處理,用的是默認的重試處理:請求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.執(zhí)行HTTP GET 請求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判斷訪問的狀態(tài)碼
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("請求出錯:" + getMethod.getStatusLine());
            }
            //5.處理HTTP響應內容
            //HTTP響應頭部信息,這里簡單打印
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //讀取HTTP響應內容,這里簡單打印網(wǎng)頁內容
            //讀取為字節(jié)數(shù)組
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //讀取為InputStream,在網(wǎng)頁內容數(shù)據(jù)量大時候推薦使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //發(fā)生致命的異常,可能是協(xié)議不對或者返回的內容有問題
            System.out.println("請檢查輸入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            //發(fā)生網(wǎng)絡異常
            System.out.println("發(fā)生網(wǎng)絡異常!");
        } finally {
            //6.釋放連接
            getMethod.releaseConnection();
        }
        return response;
    }
 
    /**
     * post請求
     * @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");
        //設置json格式傳送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        //必須設置下面這個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");
        //添加請求參數(shù)
        postMethod.addParameter("commentId", json.getString("commentId"));
 
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
 
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=telPhone", "GBK"));
        System.out.println("-----------分割線------------");
        System.out.println("-----------分割線------------");
        System.out.println("-----------分割線------------");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "telPhone");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}

總結 

到此這篇關于java遠程調用接口、URL的文章就介紹到這了,更多相關java遠程調用接口URL內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • HttpClient 在Java項目中的使用詳解

    HttpClient 在Java項目中的使用詳解

    HttpClient作為訪問Http服務的客戶端訪問程序已經被廣泛使用,提高了開發(fā)效率,也提高了代碼的健壯性。因此熟練掌握HttpClient是必需的,關于httpclient感興趣的朋友可以參考本篇文章
    2015-10-10
  • Spring Cache監(jiān)控配置與使用規(guī)范的建議

    Spring Cache監(jiān)控配置與使用規(guī)范的建議

    這篇文章主要介紹了Spring Cache監(jiān)控配置與使用規(guī)范的建議,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Mybatis-plus解決兼容oracle批量插入的示例詳解

    Mybatis-plus解決兼容oracle批量插入的示例詳解

    Mybatis-Plus 是一個 MyBatis 的增強工具,提供無侵入、損耗小的 CRUD 操作,本文給大家介紹了Mybatis-plus解決兼容oracle批量插入,文中通過大家介紹的非常詳細,需要的朋友可以參考下
    2024-11-11
  • Mac系統(tǒng)搭建JDK及JMETER過程解析

    Mac系統(tǒng)搭建JDK及JMETER過程解析

    這篇文章主要介紹了Mac系統(tǒng)搭建JDK及JMETER過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • 深入理解Java 對象和類

    深入理解Java 對象和類

    下面小編就為大家?guī)硪黄钊肜斫釰ava 對象和類。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-05-05
  • 使用FeignClient進行微服務交互方式(微服務接口互相調用)

    使用FeignClient進行微服務交互方式(微服務接口互相調用)

    這篇文章主要介紹了使用FeignClient進行微服務交互方式(微服務接口互相調用),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • mybatis QueryWrapper的條件構造之apply、last、select解析

    mybatis QueryWrapper的條件構造之apply、last、select解析

    這篇文章主要介紹了mybatis QueryWrapper的條件構造之apply、last、select,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • java 多線程交通信號燈模擬過程詳解

    java 多線程交通信號燈模擬過程詳解

    這篇文章主要介紹了java 多線程交通信號燈模擬過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07
  • java核心編程之文件過濾類FileFilter和FilenameFilter

    java核心編程之文件過濾類FileFilter和FilenameFilter

    這篇文章主要為大家詳細介紹了java文件過濾類FileFilter和FilenameFilter,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • SpringBoot中使用異步調度程序的高級方法

    SpringBoot中使用異步調度程序的高級方法

    本文主要介紹了SpringBoot中使用異步調度程序的高級方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-07-07

最新評論