在日常工作中,經(jīng)常需要跟第三方系統(tǒng)對接,我們做為客戶端,調(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請求外,還有下載文件的方法downloadFile等。
HttpURLConnection調(diào)用方法
HTTP正文的內(nèi)容是通過OutputStream流寫入,向流中寫入的數(shù)據(jù)不會立即發(fā)送到網(wǎng)絡(luò),而是存在于內(nèi)存緩沖區(qū)中,待流關(guān)閉時,根據(jù)寫入的內(nèi)容生成HTTP正文。
調(diào)用getInputStream()方法時,會返回一個輸入流,用于從中讀取服務(wù)器對于HTTP請求的返回報文
@Slf4j
public class HttpURLConnectionUtil {
? ?/**
? ? ?*
? ? ?* Description: 發(fā)送http請求發(fā)送post和json格式
? ? ?* @param url ? ? ??? ?請求URL
? ? ?* @param params ? ?json格式的請求參數(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類 用這個類來創(chuàng)建連接
? ? ? ? try {
? ? ? ? ? ? // 創(chuàng)建URL
? ? ? ? ? ? httpUrl = new URL(url);
? ? ? ? ? ? log.info("--------發(fā)起Http Post 請求 ------------- url:" + url + "---------params:" + params);
? ? ? ? ? ? // 建立連接
? ? ? ? ? ? HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
? ? ? ? ? ? //設(shè)置請求的方法為"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)的情況下不允許輸出,所以在請求輸出流之前必須調(diào)用setDoOutput(true)
? ? ? ? ? ? conn.setDoOutput(true);
? ? ? ? ? ? // 設(shè)置是否從httpUrlConnection讀入
? ? ? ? ? ? conn.setDoInput(true);
? ? ? ? ? ? //設(shè)置超時時間
? ? ? ? ? ? conn.setConnectTimeout(30000);
? ? ? ? ? ? conn.setReadTimeout(30000);
? ? ? ? ? ? conn.connect();
? ? ? ? ? ? // POST請求
? ? ? ? ? ? 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();
? ? ? ? ? ? // 斷開連接
? ? ? ? ? ? conn.disconnect();
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? log.error("--------發(fā)起Http Post 請求 異常 {}-------------", e);
? ? ? ? ? ? throw new Exception(e);
? ? ? ? }
? ? ? ? // 使用finally塊來關(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 是一個抽象類,實現(xiàn)了httpClient接口,也實現(xiàn)了java.io.Closeable;
支持連接池管理,可復(fù)用已建立的連接 PoolingHttpClientConnectionManager
通過 httpClient.close() 自動管理連接釋放
支持HTTPS訪問 HttpHost proxy = new HttpHost(“127.0.0.1”, 8080, “http”);文章來源:http://www.zghlxwxcb.cn/news/detail-861048.html
@Slf4j
public class CloseableHttpClientUtil {
?? ?/**
?? ?*url 第三方接口地址
?? ?*json 傳入的報文體,可以是dto對象,string、json等
?? ?*header 額外傳入的請求頭參數(shù)
?? ?*/?? ?
? public static String doPost(String url, Object json,Map<String,String> header) {
? ? ? ? CloseableHttpClient httpclient = HttpClientBuilder.create().build();
? ? ? ? HttpPost httpPost= new HttpPost(url);//post請求類型
? ? ? ? String result="";//返回結(jié)果
? ? ? ? String requestJson="";//發(fā)送報文體
? ? ? ? try {
? ? ? ? ?? ?requestJson=JSONObject.toJSONString(json);
? ? ? ? ? ? log.info("發(fā)送地址:"+url+"發(fā)送報文:"+requestJson);
? ? ? ? ? ? //StringEntity s = new StringEntity(requestJson, Charset.forName("UTF-8"));
? ? ? ? ? ? StringEntity s= new StringEntity(requestJson, "UTF-8");
? ? ? ??? ??? ?// post請求是將參數(shù)放在請求體里面?zhèn)鬟^去的;這里將entity放入post請求體中
? ? ? ??? ??? ?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());
? ? ? ? ? ? ? ? ? ? //也可以把返回的報文轉(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)用
//可以在項目啟動類中添加RestTemplate 的bean,后續(xù)就可以在代碼中@Autowired引入。文章來源地址http://www.zghlxwxcb.cn/news/detail-861048.html
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Slf4j
@Component
public class RestTemplateUtils {
?? ?@Autowired
?? ?private RestTemplate restTemplate;
?? ?/**
?? ? * get 請求 參數(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("請求接口:{}", urls);
?? ??? ?HttpHeaders headers = new HttpHeaders();
?? ??? ?headers.setContentType(MediaType.APPLICATION_JSON);
?? ??? ?HttpEntity<String> httpEntity = new HttpEntity<>(headers);
?? ??? ?//通用的方法exchange,這個方法需要你在調(diào)用的時候去指定請求類型,可以是get,post,也能是其它類型的請求
?? ??? ?ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
?? ??? ?if (responseEntity == null) {
?? ??? ??? ?return null;
?? ??? ?}
? ? ? ? log.info("返回報文:{}", JSON.toJSONString(responseEntity));
?? ??? ?
?? ??? ?return responseEntity.getBody();
?? ?}
?? ?
?? ?/**
?? ? * post 請求 參數(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("請求接口:{}, 請求報文:{}", 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("返回報文:{}", seqResult);
?? ??? ??? ?
?? ??? ?} catch (UnsupportedEncodingException e) {
?? ??? ??? ?log.error("接口返回異常", e);
?? ??? ?}
?? ??? ?return seqResult;
?? ?}
}
到了這里,關(guān)于java對接第三方接口的三種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!