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

java對(duì)接第三方接口的三種實(shí)現(xiàn)方式

 更新時(shí)間:2025年05月23日 16:21:27   作者:codingPower  
這篇文章主要介紹了java對(duì)接第三方接口的三種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

在日常工作中,經(jīng)常需要跟第三方系統(tǒng)對(duì)接,我們做為客戶端,調(diào)用他們的接口進(jìn)行業(yè)務(wù)處理

常用的幾種調(diào)用方式有:

  • 1.原生的Java.net.HttpURLConnection(jdk);
  • 2.再次封裝的HttpClient、CloseableHttpClient(Apache);
  • 3.Spring提供的RestTemplate;

當(dāng)然還有其他工具類進(jìn)行封裝的接口,比如hutool的HttpUtil工具類,里面除了post、get請(qǐng)求外,還有下載文件的方法downloadFile等。

HttpURLConnection調(diào)用方法

HTTP正文的內(nèi)容是通過(guò)OutputStream流寫(xiě)入,向流中寫(xiě)入的數(shù)據(jù)不會(huì)立即發(fā)送到網(wǎng)絡(luò),而是存在于內(nèi)存緩沖區(qū)中,待流關(guān)閉時(shí),根據(jù)寫(xiě)入的內(nèi)容生成HTTP正文。

調(diào)用getInputStream()方法時(shí),會(huì)返回一個(gè)輸入流,用于從中讀取服務(wù)器對(duì)于HTTP請(qǐng)求的返回報(bào)文

@Slf4j
public class HttpURLConnectionUtil {
   /**
     *
     * Description: 發(fā)送http請(qǐng)求發(fā)送post和json格式
     * @param url      	請(qǐng)求URL
     * @param params    json格式的請(qǐng)求參數(shù)
     */
    public static String doPost(String url, String params) throws Exception {

        OutputStreamWriter out = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        URL httpUrl = null; // HTTP URL類 用這個(gè)類來(lái)創(chuàng)建連接
        try {
            // 創(chuàng)建URL
            httpUrl = new URL(url);
            log.info("--------發(fā)起Http Post 請(qǐng)求 ------------- url:" + url + "---------params:" + params);

            // 建立連接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //設(shè)置請(qǐng)求的方法為"POST",默認(rèn)是GET
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);// 設(shè)置不要緩存
            conn.setInstanceFollowRedirects(true);
            //由于URLConnection在默認(rèn)的情況下不允許輸出,所以在請(qǐng)求輸出流之前必須調(diào)用setDoOutput(true)
            conn.setDoOutput(true);
            // 設(shè)置是否從httpUrlConnection讀入
            conn.setDoInput(true);
            //設(shè)置超時(shí)時(shí)間
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.connect();
            // POST請(qǐng)求
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(params);
            out.flush();
            // 讀取響應(yīng)
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                response.append(lines);
            }
            reader.close();
            // 斷開(kāi)連接
            conn.disconnect();
        } catch (Exception e) {
            log.error("--------發(fā)起Http Post 請(qǐng)求 異常 {}-------------", e);
            throw new Exception(e);
        }
        // 使用finally塊來(lái)關(guān)閉輸出流、輸入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(String.valueOf(ex));
            }
        }
        return response.toString();
    }
}

CloseableHttpClient調(diào)用

CloseableHttpClient 是一個(gè)抽象類,實(shí)現(xiàn)了httpClient接口,也實(shí)現(xiàn)了java.io.Closeable;

支持連接池管理,可復(fù)用已建立的連接 PoolingHttpClientConnectionManager

通過(guò) httpClient.close() 自動(dòng)管理連接釋放

支持HTTPS訪問(wèn) HttpHost proxy = new HttpHost(“127.0.0.1”, 8080, “http”);

@Slf4j
public class CloseableHttpClientUtil {
	/**
	*url 第三方接口地址
	*json 傳入的報(bào)文體,可以是dto對(duì)象,string、json等
	*header 額外傳入的請(qǐng)求頭參數(shù)
	*/	
  public static String doPost(String url, Object json,Map<String,String> header) {

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpPost= new HttpPost(url);//post請(qǐng)求類型
        String result="";//返回結(jié)果
        String requestJson="";//發(fā)送報(bào)文體
        try {
        	requestJson=JSONObject.toJSONString(json);
            log.info("發(fā)送地址:"+url+"發(fā)送報(bào)文:"+requestJson);
            //StringEntity s = new StringEntity(requestJson, Charset.forName("UTF-8"));
            StringEntity s= new StringEntity(requestJson, "UTF-8");
       		// post請(qǐng)求是將參數(shù)放在請(qǐng)求體里面?zhèn)鬟^(guò)去的;這里將entity放入post請(qǐng)求體中
       		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setEntity(s);
            if(header!=null){
                Set<String> strings = header.keySet();
                for(String str:strings){
                    httpPost.setHeader(str,header.get(str));
                }
            }
            HttpResponse res = httpclient.execute(httpPost);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(res.getEntity());
                    //也可以把返回的報(bào)文轉(zhuǎn)成json類型
                    // JSONObject  response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
     		//此處可以加入記錄日志的方法
            // 關(guān)閉連接,釋放資源
           if (httpclient!= null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
        return result;
    }
}

RestTemplate調(diào)用

//可以在項(xiàng)目啟動(dòng)類中添加RestTemplate 的bean,后續(xù)就可以在代碼中@Autowired引入。
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Slf4j
@Component
public class RestTemplateUtils {
	@Autowired
	private RestTemplate restTemplate;

	/**
	 * get 請(qǐng)求 參數(shù)在url后面  http://xxxx?aa=xxx&page=0&size=10";
	 * @param urls 
	 * @return string
	 */
	public String doGetRequest(String urls) {
		
		URI uri = UriComponentsBuilder.fromUriString(urls).build().toUri();
		log.info("請(qǐng)求接口:{}", urls);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> httpEntity = new HttpEntity<>(headers);
		//通用的方法exchange,這個(gè)方法需要你在調(diào)用的時(shí)候去指定請(qǐng)求類型,可以是get,post,也能是其它類型的請(qǐng)求
		ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
		if (responseEntity == null) {
			return null;
		}
        log.info("返回報(bào)文:{}", JSON.toJSONString(responseEntity));
		
		return responseEntity.getBody();
	}
	
	/**
	 * post 請(qǐng)求 參數(shù)在 request里;
	 * @param url, request
	 * @return string
	 */
	public String doPostRequest(String url, Object request){
		URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();

		String requestStr= JSONObject.toJSONString(request);
		log.info("請(qǐng)求接口:{}, 請(qǐng)求報(bào)文:{}", url, requestStr);
		HttpHeaders headers = new HttpHeaders();	
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> httpEntity = new HttpEntity<>(requestStr, headers);
		ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
				
		if (responseEntity == null) {
			return null;
		}
		
		String seqResult = "";
		try {
			if(responseEntity.getBody() != null ) {		
				if(responseEntity.getBody().contains("9001")) {
					seqResult = new String(responseEntity.getBody().getBytes("ISO8859-1"),"utf-8");
				}else {
					seqResult = new String(responseEntity.getBody().getBytes(),"utf-8");	
				}											
			}
			
			log.info("返回報(bào)文:{}", seqResult);
			
		} catch (UnsupportedEncodingException e) {
			log.error("接口返回異常", e);
		}

		return seqResult;
	}
}

總結(jié)

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

相關(guān)文章

最新評(píng)論