该示例展示如何调用对方写好的http接口,数据格式对方需要双方协调定义好。
思路如下:我方调用对方接口(另一个服务器上已写好,不同域名,不同端口,需要进行跨域),传递必要参数,如id等,对方接受参数进行查询,查询到的数据封装成json格式返回,我方接收到的是一个流对象,需要转换成json字符串,再把json字符串转换成对象,封装到结果集里返回(这里返回的是调用我方接口的使用者,如手机app调用我的接口)。
@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);
//双方定义好的数据格式
CapResultBean jb = JsonUtil.jsonStrToPo(jo, CapResultBean.class);
boolean success = jb.isSuccess();
if(success == true) {
return ResponseResult.ok(jb.getObj()); //ResponseResult是自定义的结果集
}
return ResponseResult.build(500, "服务器异常");
}
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() {
}
/**
*根据Url发送GET请求
*
* @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);
/**请求发送成功,并得到响应 **/
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("远程数据获取失败!", e);
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
*描述: 发起http请求并获取结果
*
* @param requestUrl
*请求地址
* @param requestMethod
*请求方式(GET、POST)
* @param outputStr
*提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
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);
//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if(StringUtils.equals(dataType, "json")) {
httpUrlConn.setRequestProperty("Content-type", "application/json");
}
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
//当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
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;
}
}
免费学习编程:www.51program.com
全套Java课程免费分享请关注微信公众号:我要编程(微信号:oset51)
技术交流群:259657781
网友评论