java遠程調(diào)用接口、URL的方式代碼
一:httpUrlConnection
1.獲取HttpURLConnection連接對象
/**
* 獲取HttpURLConnection連接對象
* @param url 遠程調(diào)用的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.遠程調(diào)用代碼
/**
* 遠程調(diào)用登錄接口
*/
public void accessLoginUrl(){
//遠程調(diào)用接口的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);
}
//獲取響應結(jié)果
String response = byteArrayOutputStream.toString();
ObjectMapper objectMapper = new ObjectMapper();
RespBean respBean = objectMapper.readValue(response, RespBean.class);
String userTicket = (String) respBean.getObject();
System.out.println("遠程調(diào)用接口的返回值"+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 類可用于在應用中調(diào)用 rest 服務,它簡化了與 http 服務的通信方式,統(tǒng)一了 RESTful 的標準,封裝了 http 鏈接, 我們只需要傳入 url 及返回值類型即可。相較于之前常用的 HttpClient,RestTemplate 是一種更優(yōu)雅的調(diào)用 RESTful 服務的方式。
2.在 Spring 應用程序中訪問第三方 REST 服務與使用 Spring RestTemplate 類有關(guān)。RestTemplate 類的設計原則與許多其他 Spring 模板類(例如 JdbcTemplate、JmsTemplate)相同,為執(zhí)行復雜任務提供了一種具有默認行為的簡化方法。
3.RestTemplate 默認依賴 JDK 提供 http 連接的能力(HttpURLConnection),如果有需要的話也可以通過 setRequestFactory 方法替換為例如 Apache HttpComponents、Netty 或 OkHttp 等其它 HTTP library。
4.考慮到 RestTemplate 類是為調(diào)用 REST 服務而設計的,因此它的主要方法與 REST 的基礎(chǔ)緊密相連就不足為奇了,后者是 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為需要遠程調(diào)用接口傳遞的參數(shù)
2.3 示例代碼
/**
* 遠程調(diào)用登錄接口
*/
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)方法或者調(diào)用setEntity(HttpEntity entity)方法設置參數(shù);
4,調(diào)用httpClient的execute(HttpUriRequest request)執(zhí)行請求,返回結(jié)果是一個response對象;
5,通過response的getHeaders(String name)或getAllHeaders()可獲得請求頭部信息,getEntity()方法獲取HttpEntity對象,該對象包裝了服務器的響應內(nèi)容。
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響應內(nèi)容;
* 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響應內(nèi)容
//HTTP響應頭部信息,這里簡單打印
Header[] headers = getMethod.getResponseHeaders();
for(Header h : headers) {
System.out.println(h.getName() + "---------------" + h.getValue());
}
//讀取HTTP響應內(nèi)容,這里簡單打印網(wǎng)頁內(nèi)容
//讀取為字節(jié)數(shù)組
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("-----------response:" + response);
//讀取為InputStream,在網(wǎng)頁內(nèi)容數(shù)據(jù)量大時候推薦使用
//InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
//發(fā)生致命的異常,可能是協(xié)議不對或者返回的內(nèi)容有問題
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));
}
}總結(jié)
到此這篇關(guān)于java遠程調(diào)用接口、URL的文章就介紹到這了,更多相關(guān)java遠程調(diào)用接口URL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳述IntelliJ IDEA遠程調(diào)試Tomcat的方法(圖文)
本篇文章主要介紹了詳述IntelliJ IDEA遠程調(diào)試Tomcat的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
Java循環(huán)結(jié)構(gòu)之多重循環(huán)及continue?break
這篇文章主要介紹了Java循環(huán)結(jié)構(gòu)之多重循環(huán)及continue?break,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-09-09
SpringBoot啟動時執(zhí)行自定義內(nèi)容的五種方法
在Spring Boot應用開發(fā)中,我們經(jīng)常需要在應用啟動時執(zhí)行一些初始化邏輯,比如加載配置、初始化數(shù)據(jù)、啟動后臺任務等,Spring Boot提供了多種方式來實現(xiàn)這一需求,本文將詳細介紹5種常用的方法,需要的朋友可以參考下2025-10-10
java中switch case語句需要加入break的原因解析
這篇文章主要介紹了java中switch case語句需要加入break的原因解析的相關(guān)資料,需要的朋友可以參考下2017-07-07
Springboot教程之如何設置springboot熱重啟
這篇文章主要介紹了Springboot教程之如何設置springboot熱重啟,本文通過實例圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07

