該示例展示如何調(diào)用對(duì)方寫好的http接口,數(shù)據(jù)格式對(duì)方需要雙方協(xié)調(diào)定義好。
思路如下:我方調(diào)用對(duì)方接口(另一個(gè)服務(wù)器上已寫好锭沟,不同域名,不同端口壕探,需要進(jìn)行跨域)冈钦,傳遞必要參數(shù),如id等李请,對(duì)方接受參數(shù)進(jìn)行查詢瞧筛,查詢到的數(shù)據(jù)封裝成json格式返回,我方接收到的是一個(gè)流對(duì)象导盅,需要轉(zhuǎn)換成json字符串较幌,再把json字符串轉(zhuǎn)換成對(duì)象,封裝到結(jié)果集里返回(這里返回的是調(diào)用我方接口的使用者白翻,如手機(jī)app調(diào)用我的接口)乍炉。
@RequestMapping(value = "details", method = RequestMethod.GET)
public ResponseResult details(@RequestParam("processInstanceId") String processInstanceId,
String recordNumber,Integer pageSize, HttpServletRequest request, HttpServletResponse response) {
String url =
"http://218.95.182.35:5555/dcxm/Compass/workflow/data/hisInfo?processInstanceId="+processInstanceId;
String jo = HttpUtils.httpRequest(url, "GET", null,null);
//雙方定義好的數(shù)據(jù)格式
CapResultBean jb = JsonUtil.jsonStrToPo(jo, CapResultBean.class);
????boolean success = jb.isSuccess();
if(success == true) {
return ResponseResult.ok(jb.getObj()); //ResponseResult是自定義的結(jié)果集
}
return ResponseResult.build(500, "服務(wù)器異常");
}
HttpUtils工具類:
package com.hollysmart.app.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONObject;
public abstract class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private HttpUtils() {
}
/**
*根據(jù)Url發(fā)送GET請(qǐng)求
?*
?* @param url
?* @return
?*/
public static String get(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
String result = "";
try {
response = httpClient.execute(httpGet);
/**請(qǐng)求發(fā)送成功,并得到響應(yīng) **/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
}
} catch (Exception e) {
logger.error("遠(yuǎn)程數(shù)據(jù)獲取失斅蒜伞岛琼!", e);
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
*描述: 發(fā)起http請(qǐng)求并獲取結(jié)果
?*
?* @param requestUrl
*請(qǐng)求地址
?* @param requestMethod
*請(qǐng)求方式(GET、POST)
?* @param outputStr
*提交的數(shù)據(jù)
* @return JSONObject(通過(guò)JSONObject.get(key)的方式獲取json對(duì)象的屬性值)
?*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr,String dataType) {
StringBuffer buffer = new StringBuffer();
String result = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//設(shè)置請(qǐng)求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if(StringUtils.equals(dataType, "json")) {
httpUrlConn.setRequestProperty("Content-type", "application/json");
}
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
//當(dāng)有數(shù)據(jù)需要提交時(shí)
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
//注意編碼格式巢株,防止中文亂碼
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//將返回的輸入流轉(zhuǎn)換成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
result = buffer.toString();
//jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
免費(fèi)學(xué)習(xí)編程:www.51program.com
全套Java課程免費(fèi)分享請(qǐng)關(guān)注微信公眾號(hào):我要編程(微信號(hào):oset51)
技術(shù)交流群:259657781