實例詳解Java調(diào)用第三方接口方法
一、 通過JDK網(wǎng)絡類Java.net.HttpURLConnection
1.java.net包下的原生java api提供的http請求
使用步驟:
1、通過統(tǒng)一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection)。
2、設置請求的參數(shù)。
3、發(fā)送請求。
4、以輸入流的形式獲取返回內(nèi)容。
5、關(guān)閉輸入流。
2.HttpClientUtil工具類
/**
* jdk 調(diào)用第三方接口
* @author hsq
*/
public class HttpClientUtil2 {
/**
* 以post方式調(diào)用對方接口方法
* @param pathUrl
*/
public static String doPost(String pathUrl, String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打開和url之間的連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//設定請求的方法為"POST",默認是GET
//post與get的不同之處在于post的參數(shù)不是放在URL字串里面,而是放在http請求的正文內(nèi)。
conn.setRequestMethod("POST");
//設置30秒連接超時
conn.setConnectTimeout(30000);
//設置30秒讀取超時
conn.setReadTimeout(30000);
// 設置是否向httpUrlConnection輸出,因為這個是post請求,參數(shù)要放在http正文內(nèi),因此需要設為true, 默認情況下是false;
conn.setDoOutput(true);
// 設置是否從httpUrlConnection讀入,默認情況下是true;
conn.setDoInput(true);
// Post請求不能使用緩存
conn.setUseCaches(false);
//設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //維持長鏈接
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//連接,從上述url.openConnection()至此的配置必須要在connect之前完成,
conn.connect();
/**
* 下面的三句代碼,就是調(diào)用第三方http接口
*/
//獲取URLConnection對象對應的輸出流
//此處getOutputStream會隱含的進行connect(即:如同調(diào)用上面的connect()方法,所以在開發(fā)中不調(diào)用上述的connect()也可以)。
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//發(fā)送請求參數(shù)即數(shù)據(jù)
out.write(data);
//flush輸出流的緩沖
out.flush();
/**
* 下面的代碼相當于,獲取調(diào)用第三方http接口后返回的結(jié)果
*/
//獲取URLConnection對象對應的輸入流
InputStream is = conn.getInputStream();
//構(gòu)造一個字符流緩存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//關(guān)閉流
is.close();
//斷開連接,disconnect是在底層tcp socket鏈接空閑時才切斷,如果正在被其他線程使用就不切斷。
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)用對方接口方法
* @param pathUrl
*/
public static String doGet(String pathUrl){
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打開和url之間的連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//設定請求的方法為"GET",默認是GET
//post與get的不同之處在于post的參數(shù)不是放在URL字串里面,而是放在http請求的正文內(nèi)。
conn.setRequestMethod("GET");
//設置30秒連接超時
conn.setConnectTimeout(30000);
//設置30秒讀取超時
conn.setReadTimeout(30000);
// 設置是否向httpUrlConnection輸出,因為這個是post請求,參數(shù)要放在http正文內(nèi),因此需要設為true, 默認情況下是false;
conn.setDoOutput(true);
// 設置是否從httpUrlConnection讀入,默認情況下是true;
conn.setDoInput(true);
// Post請求不能使用緩存(get可以不使用)
conn.setUseCaches(false);
//設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //維持長鏈接
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//連接,從上述url.openConnection()至此的配置必須要在connect之前完成,
conn.connect();
/**
* 下面的代碼相當于,獲取調(diào)用第三方http接口后返回的結(jié)果
*/
//獲取URLConnection對象對應的輸入流
InputStream is = conn.getInputStream();
//構(gòu)造一個字符流緩存
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();
//斷開連接,disconnect是在底層tcp socket鏈接空閑時才切斷,如果正在被其他線程使用就不切斷。
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("進入到api接口.......");
return Result.success("hello world api get 接口數(shù)據(jù)");
}
@PostMapping("/postHello")
public Result postHelloWord(@RequestBody User user){
log.info("進入post 方法.....");
System.out.println(user.toString());
return Result.success("hello world api post接口數(shù)據(jù)");
}
}

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

二、通過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請求方式
* 使用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.釋放連接。
* @author hsq
*/
public class HttpClientUtil {
/**
* @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=utf-8");
//必須設置下面這個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("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("進入到api接口.......");
return Result.success("hello world api get 接口數(shù)據(jù)");
}
@PostMapping("/postHello")
public Result postHelloWord(@RequestBody User user){
log.info("進入post 方法.....");
System.out.println(user.toString());
return Result.success("hello world api post接口數(shù)據(jù)");
}
}
4.測試類
@Test
public void testApi() {
//測試get方法
String s = HttpClientUtil.doGet("http://localhost:9092/api/getHello", "UTF-8");
System.out.println("get方法:"+s);
//測試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é)果:

三、通過Spring的RestTemplate
1.引入依賴
導入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實現(xiàn)類
/**
* @author hsq
*/
@Component
public class RestTemplateToInterface {
@Autowired
private RestTemplate restTemplate;
/**
* 以get方式請求第三方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方式請求第三方http接口 getForObject
* 返回值返回的是響應體,省去了我們再去getBody()
* @param url
* @return
*/
public Result doGetWith2(String url){
Result result = restTemplate.getForObject(url, Result.class);
return result;
}
/**
* 以post方式請求第三方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方式請求第三方http接口 postForEntity
* 返回值返回的是響應體,省去了我們再去getBody()
* @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("進入到api接口.......");
return Result.success("hello world api get 接口數(shù)據(jù)");
}
@PostMapping("/postHello")
public Result postHelloWord(@RequestBody User user){
log.info("進入post 方法.....");
System.out.println(user.toString());
return Result.success("hello world api post接口數(shù)據(jù)");
}
}

5.測試類
//注入使用
@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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot使用JdbcTemplate完成對數(shù)據(jù)庫的增刪改查功能
這篇文章主要介紹了springboot使用JdbcTemplate完成對數(shù)據(jù)庫的增刪改查功能,需要的朋友可以參考下2017-12-12
基于spring+quartz的分布式定時任務框架實現(xiàn)
在Spring中的定時任務功能,最好的辦法當然是使用Quartz來實現(xiàn)。這篇文章主要介紹了基于spring+quartz的分布式定時任務框架實現(xiàn),有興趣的可以了解一下。2017-01-01
Java使用application.property讀取文件里面的值
本文通過實例代碼給大家介紹了Java使用application.property讀取文件里面的值,需要的朋友可以參考下2018-10-10
Spring?Data?Jpa?中原生查詢?REGEXP?的使用詳解
這篇文章主要介紹了Spring?Data?Jpa?中原生查詢?REGEXP?的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

