1.使用场景
两个公司进行合作,但是是两个毫不相关的项目,所以就需要使用http请求远程访问接口获取返回值。
2.如何做到
使用http请求建立连接访问接口获取返回值并解析
调用其他系统接口工具类如下
/**
* @author wangli
* @data 2022/3/24 9:49
* @Description:http请求工具类
*/
public class HttpClientUtils {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
private Map<String,String> map;
public HttpClientUtils(Map<String,String> map){
this.map = map;
}
/*
* 根据map获取请求参数
*/
public String getParam(){
StringBuilder sb = new StringBuilder();
Set<String> keySet = map.keySet();
for (String string : keySet) {
sb.append(string + "=" + map.get(string) + "&");
}
return sb.toString();
}
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
//System.out.println("发送get请求********************"+urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
connection.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
connection.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
//建立长连接
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
log.info(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("X-APP-KEY", "f4900c0c-39ce-4852-bfcf-595e7b877e31");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}else{
InputStream errorStream = conn.getErrorStream();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(errorStream,"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
log.error("响应失败:"+conn.getResponseCode()+",响应信息"+conn.getResponseMessage()+",返回信息:"+result);
}
}catch (Exception e) {
log.error("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
log.error("关闭流异常"+ex);
ex.printStackTrace();
}
}
return result;
}
/*
*post请求,参数为json类型
*/
public static String sendJsonPost(String url, String jsonParam) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");
// 发送请求参数
out.write(jsonParam);
// flush输出流的缓冲
out.flush();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}else{
log.error("响应失败");
}
}catch (Exception e) {
log.error("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
log.error("关闭流异常"+ex);
ex.printStackTrace();
}
}
return result;
}
public static String getBrowserName(String agent) {
if(agent.indexOf("msie 7")>0){
return "ie7";
}else if(agent.indexOf("msie 8")>0){
return "ie8";
}else if(agent.indexOf("msie 9")>0){
return "ie9";
}else if(agent.indexOf("msie 10")>0){
return "ie10";
}else if(agent.indexOf("msie")>0){
return "ie";
}else if(agent.indexOf("opera")>0){
return "opera";
}else if(agent.indexOf("opera")>0){
return "opera";
}else if(agent.indexOf("firefox")>0){
return "firefox";
}else if(agent.indexOf("webkit")>0){
return "webkit";
}else if(agent.indexOf("gecko")>0 && agent.indexOf("rv:11")>0){
return "ie11";
}else{
return "Others";
}
}
/**
* http post请求方式
* @param urlStr
* @param params
*
**/
public static String post(String urlStr,Map<String,String> params){
URL connect;
StringBuffer data = new StringBuffer();
try {
connect = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
//connection.setRequestProperty("accept", "*/*");
//connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //**很重要,指定编码集
// connection.setRequestProperty("Content-Type","text/html;charset=UTF-8");
//connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//conn.setRequestProperty("Cookie", cookiesAll.toString()); 设置cookie 若需要登录操作
OutputStreamWriter paramout = new OutputStreamWriter(
connection.getOutputStream(),"utf-8");
String paramsStr = "";
for(String param : params.keySet()){
paramsStr += "&" + param + "=" + params.get(param);
}
System.out.println(paramsStr);
if(!paramsStr.isEmpty()){
paramsStr = paramsStr.substring(1);
}
paramsStr="tablename=T_YW_AJ_SXCS&index=id&rows=[{%22addrcode%22:null,%22addrdesc%22:%22%E5%B9%BF%E4%B8%9C%E7%9C%81%E6%B7%B1%E5%9C%B3%E5%B8%82%E7%A6%8F%E7%94%B0%E5%8C%BA%E9%A6%99%E8%9C%9C%E6%B9%96%E8%A1%97%E9%81%93%E7%AB%B9%E5%9B%AD%E7%A4%BE%E5%8C%BA%E5%BB%BA%E4%B8%9A1%E6%A0%8B%E3%80%812%E6%A0%8B%E5%8D%95%E8%BA%AB%E5%85%AC%E5%AF%9325%22,%22address%22:%221%E5%9D%8A25-2%22,%22approved_type%22:null,%22area%22:%22%E6%B2%99%E5%98%B4%E7%A4%BE%E5%8C%BA%22,%22audit_time%22:null,%22audit_user%22:null,%22business_area%22:%22100%E3%8E%A1%E4%BB%A5%E4%B8%8B%22,%22business_card_no%22:%22%E6%97%A0%22,%22business_type%22:%22%E6%97%A7%E8%B4%A7%E4%B9%B0%E5%8D%96%22,%22bzdz%22:%22%E5%B9%BF%E4%B8%9C%E7%9C%81%E6%B7%B1%E5%9C%B3%E5%B8%82%E7%A6%8F%E7%94%B0%E5%8C%BA%E9%A6%99%E8%9C%9C%E6%B9%96%E8%A1%97%E9%81%93%E7%AB%B9%E5%9B%AD%E7%A4%BE%E5%8C%BA%E5%BB%BA%E4%B8%9A1%E6%A0%8B%E3%80%812%E6%A0%8B%E5%8D%95%E8%BA%AB%E5%85%AC%E5%AF%9325%22,%22checkstate%22:%220%22,%22cjsj%22:%222017-03-06%2015:46:34%22,%22code%22:null,%22createtime%22:%222018-03-29%2010:41:18%22,%22creator%22:null,%22creatorid%22:null,%22dl%22:null,%22dldm%22:null,%22doublecheck_time%22:null,%22dywgcode%22:null,%22fw%22:%2225%22,%22fwdm%22:%224403040070080500041000025%22,%22grid%22:%22440304005005000%22,%22grid_name%22:null,%22gxsj%22:null,%22id%22:%224A0AE7E0E782BD8EE0530142BE0ABB93%22,%22is_business_card%22:%22%E5%90%A6%22,%22is_up%22:%222%22,%22isadd%22:null,%22ischange%22:null,%22ischeck%22:%220%22,%22isdelete%22:0,%22isdoublecheck%22:null,%22istrouble%22:null,%22last_check_time%22:null,%22lat%22:null,%22ld%22:%221%E6%A0%8B%E3%80%812%E6%A0%8B%E5%8D%95%E8%BA%AB%E5%85%AC%E5%AF%93%22,%22lddm%22:%224403040070080500041%22,%22logouter%22:null,%22logouterid%22:null,%22logouttime%22:null,%22lon%22:null,%22name%22:%22%E6%97%A0%E5%90%8D%E9%BA%BB%E5%B0%86%E5%BA%97%22,%22operator_card_id%22:null,%22operator_name%22:%22%E9%AB%98%E9%87%91%E5%87%A4%22,%22operator_tel%22:%2283440400%22,%22owner_card_id%22:null,%22owner_name%22:null,%22owner_tel%22:null,%22photo%22:null,%22place_type%22:%2260021%22,%22qu%22:null,%22qudm%22:null,%22remark%22:null,%22sheng%22:null,%22shengdm%22:null,%22shi%22:null,%22shidm%22:null,%22sjly%22:null,%22sjlyfs%22:null,%22sq%22:%22%E6%B2%99%E5%98%B4%E7%A4%BE%E5%8C%BA%22,%22sqdm%22:%22440304004004%22,%22sqid%22:%22440304004004%22,%22status%22:%220%22,%22street%22:%22%E6%B2%99%E5%A4%B4%E8%A1%97%E9%81%93%22,%22streetid%22:%22440304004%22,%22times%22:null,%22update_id%22:null,%22update_name%22:null,%22update_time%22:null,%22xq%22:%22%E5%BB%BA%E4%B8%9A%22,%22xqdm%22:null,%22zx_audit_time%22:null,%22zx_audit_user%22:null}]";
paramout.write(paramsStr);
paramout.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
data.append(line);
}
paramout.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return data.toString();
}
/**
* http post请求方式
* @param urlStr
* @param params
*
**/
public static String post(String urlStr,Map<String,String> params,JSONObject obj){
URL connect;
StringBuffer data = new StringBuffer();
try {
connect = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//conn.setRequestProperty("Cookie", cookiesAll.toString()); 设置cookie 若需要登录操作
OutputStreamWriter paramout = new OutputStreamWriter(
connection.getOutputStream(),"UTF-8");
String paramsStr = "";
for(String param : params.keySet()){
paramsStr += "&" + param + "=" + params.get(param);
}
if(!paramsStr.isEmpty()){
paramsStr = paramsStr.substring(1);
}
paramout.write(paramsStr);
paramout.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
data.append(line);
}
paramout.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
obj.put("status", "2");
String mes=e.getMessage();
if(mes.indexOf("Connection timed out: connect")!=-1){
obj.put("fReason", "连接超时");
}
return data.toString();
}
obj.put("status", "1");
return data.toString();
}
public static String sendGet(String url, String param,JSONObject obj) {
StringBuilder sb=new StringBuilder();
//String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
//System.out.println("发送get请求********************"+urlNameString);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
connection.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
connection.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
//建立长连接
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
log.info(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
log.error("发送GET请求出现异常!" + e);
e.printStackTrace();
obj.put("status", "2");
String mes=e.getMessage();
if(mes.indexOf("Connection timed out: connect")!=-1){
obj.put("fReason", "连接超时");
}
return sb.toString();
}
//使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
obj.put("status", "1");
return sb.toString();
}
/**
* 获取当前网络ip
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
//wfs.dps授权测试方法
public static void testPost() throws IOException{
Map<String,String> params = new HashMap<String,String>();
/*
//wfs授权配置
params.put("orderid", "");
params.put("agencyrplinkage", "http://192.168.100.41:80/geostar/NoDelete/");
params.put("metadataid", "8e4baaad-7300-4bc8-8e65-1e27fe27c20b");
params.put("restitle", "NoDelete");
params.put("restype", "service");
params.put("orderType", "2");
params.put("authorizationId", "863d9e9c-63f2-47c7-9ea4-750c4bb93fa5");
params.put("authorizationName", "智慧城市");
JSONObject interfacename = new JSONObject();
interfacename.put("WFST", "GetCapabilities,DescribeFeatureType,GetFeature,Transaction,LockFeature");
params.put("interfacename", interfacename.toJSONString());
JSONObject layers = new JSONObject();
layers.put("WFST", "V_YS_RK_CZRK,T_YS_W_BASE,V_YS_ZZ_BASE");
params.put("layers", layers.toJSONString());
params.put("layersId", "");
params.put("maxVisitTimes", "0");
JSONArray authorizerArr = new JSONArray();
JSONObject authorizerArr1 = new JSONObject();
authorizerArr1.put("authorizerName", "ajuser");
authorizerArr1.put("authorizerId", "6ff8e3d1-b511-4a98-b1e4-3cae1d01ec34");
authorizerArr.add(authorizerArr1);
params.put("authorizerArr", authorizerArr.toJSONString());
params.put("startdate", "2018-02-27");
params.put("enddate", "2018-05-27");
params.put("startip", "192.168.40.1,192.168.40.121");
params.put("endip", "192.168.40.100,192.168.40.121");
params.put("rangeFileId", "");
JSONArray propertyArr = new JSONArray();
JSONObject propertyArr1 = new JSONObject();
propertyArr1.put("propertyName", "JDCODE");
propertyArr1.put("relation", "2");
propertyArr1.put("propertyVal", "440304010");
propertyArr1.put("orderId", "");
propertyArr1.put("layer", "V_YS_RK_CZRK");
propertyArr1.put("logic", "0");
propertyArr.add(propertyArr1);
JSONObject propertyArr2 = new JSONObject();
propertyArr2.put("propertyName", "DYWGCODE");
propertyArr2.put("relation", "3");
propertyArr2.put("propertyVal", "440304001010");
propertyArr2.put("orderId", "");
propertyArr2.put("layer", "V_YS_RK_CZRK");
propertyArr2.put("logic", "0");
propertyArr.add(propertyArr2);
params.put("propertyArr", propertyArr.toJSONString());
params.put("dpsDataSetArr", "[]");
params.put("dpsPropertyArr", "[]");
params.put("authorizeModel", "1");
params.put("username","admin");*/
//dps授权配置
// params.put("orderid", "");//订单id
// params.put("agencyrplinkage", "http://192.168.100.41:80/geostar/NoDelete_DPS1/");//wfs请求地址,参数为代理地址
// params.put("metadataid", "fd75fa56-2580-4e2b-94c5-b5200c11b312");//wfs服务在服务中心中的ID
// params.put("restitle", "NoDelete_DPS1");//服务名称
// params.put("restype", "service");//固定
// params.put("orderType", "2");//固定
// params.put("authorizationId", "863d9e9c-63f2-47c7-9ea4-750c4bb93fa5");//授权部门id
// params.put("authorizationName", "智慧城市");//授权部门名称
//
// JSONObject interfacename = new JSONObject();
// interfacename.put("DPS", "GetCapabilities,GetCatalog,GetDataSetList,DescribeDataSet,Query,Analysis");//授权接口
// params.put("interfacename", interfacename.toJSONString());
//
// JSONObject layers = new JSONObject();
// layers.put("DPS", "");//留空
// params.put("layers", layers.toJSONString());//授权图层
//
// params.put("layersId", "");//留空
// params.put("maxVisitTimes", "0");//最大访问次数
//
// JSONArray authorizerArr = new JSONArray();
// JSONObject authorizerArr1 = new JSONObject();
// authorizerArr1.put("authorizerName", "ajuser");
// authorizerArr1.put("authorizerId", "6ff8e3d1-b511-4a98-b1e4-3cae1d01ec34");
// authorizerArr.add(authorizerArr1);
// params.put("authorizerArr", authorizerArr.toJSONString());//授权用户id和用户名
//
// params.put("startdate", "2018-02-27");//访问限制开始时间
// params.put("enddate", "2018-05-27");//访问限制结束时间
// params.put("startip", "192.168.40.1,192.168.40.121");//部门IP
// params.put("endip", "192.168.40.100,192.168.40.121");
// params.put("rangeFileId", "");//留空
// params.put("propertyArr", "[]");//logic:条件关系 0为and,1为or relation 关系运算 0:小于 1:小于等于 2:等于 3:模糊等于 4:大于 5:大于等于 6:不等于
// params.put("dpsDataSetArr", "[]");//propertyShow:该数据集允许访问的字段,不限制为""
params.put("rows", "[{\"address\":\"jrjfhfhfn\",\"bjtime\":null,\"community\":null,\"community_id\":null,\"creater_dept\":\"城管科\",\"creater_deptid\":\"44030400232\",\"creater_id\":\"wangjing1\",\"creater_name\":\"王晶\",\"ctime\":\"2017-06-07 16:24:45\",\"dbtime\":null,\"event_code\":\"440304002201706070001\",\"event_content\":\"xndndn\",\"event_keyword\":null,\"event_lv\":\"01\",\"event_name\":\"深城管2017字第146140号440304002201706070001\",\"event_source\":\"90\",\"event_time\":\"2017-07-11 00:22:00\",\"event_type\":null,\"event_typeid\":null,\"fbtime\":null,\"flowkey\":null,\"flowstate\":null,\"flowstateid\":null,\"gd_event_type\":null,\"gd_event_typeid\":null,\"gdtime\":null,\"gq_remark\":null,\"gq_type\":null,\"gqtime\":null,\"grid_code\":null,\"grid_name\":null,\"isdelete\":\"1\",\"pjtime\":null,\"point_x\":null,\"point_y\":null,\"pstime\":null,\"remark\":null,\"report_address\":null,\"report_code\":\"hnfndndjcj\",\"report_code_type\":\"sfz\",\"report_name\":\"bdbfncn\",\"report_phone\":null,\"source_blsx\":null,\"source_dept\":null,\"source_deptid\":null,\"source_id\":null,\"state\":\"-1\",\"street\":null,\"street_id\":null,\"systemid\":\"d811878b964f49e688f6765db3cfcc5d\",\"templateid\":null,\"time_limit\":8,\"time_sl\":60,\"utime\":\"2017-06-07 16:24:45\",\"geometry_type\":\"POINT\"}]");
params.put("index", "systemid");//1是按用户,0是按部门,如果部门用户都授权还是1
params.put("tablename","T_FB_EVENT_INFO");//当前登录用户
//打印参数
/* Set set = params.entrySet();
for(Iterator iter = set.iterator();iter.hasNext();){
Map.Entry entry = (Map.Entry)iter.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
String paramsStr = "";
for(String param : params.keySet()){
paramsStr += "&" + param + "=" + URLEncoder.encode(params.get(param),"UTF-8");
} */
String r = post("http://localhost:8080/Portal/api/wfsApplicationData/insertYwData", params);
System.out.println(r);
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param,String contentType) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(30000);//设置连接主机超时(单位:毫秒)
conn.setReadTimeout(30000);//设置从主机读取数据超时(单位:毫秒)
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
if(contentType!=null && (!"".equals(contentType))){
conn.setRequestProperty("Content-Type", contentType);
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");
// 发送请求参数
out.write(param);
// flush输出流的缓冲
out.flush();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
}else{
InputStream errorStream = conn.getErrorStream();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(errorStream,"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
log.error("响应失败:"+conn.getResponseCode()+",响应信息"+conn.getResponseMessage()+",返回信息:"+result);
}
}catch (Exception e) {
log.error("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
log.error("关闭流异常"+ex);
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) throws Exception {
testPost();
}
}
使用如上工具类
可以将请求和参数传入,只需要合作单位提供接口url以及参数,即可远程访问
举例如下
@Override
@SystemLog(descrption = "远程调用接口获取详细信息", type = "查询", systemCode = Constants.SYSTEM_MODELCODE_COLLECT, modelName = "块地图定位")
@GetMapping("/getDtdw")
@ApiOperation(value = "远程调用接口获取详细信息 wangli", notes = "远程调用接口获取详细信息", response = StandardResult.class)
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "accessToken", value = "令牌", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "ztdz", value = "主体地址", required = true, dataType = "String")
})
public StandardResult getDtdw(@RequestParam String ztdz) {
try {
// todo :远程调用接口获取详细信息
int time = (int) (System.currentTimeMillis() / 1000);
Map<String, Object> map = new HashMap<>();
String url = "http://IP:端口/路径?user=nsltt&time=" + time + "&secret=" + MD5Utils.md5(time + "xxxx");
String data = HttpClientUtils.sendGet(url);
logger.info("data==========4" + data);
JSONObject obj = JSON.parseObject(data);
Object data1 = obj.get("data");
String tokenData = JSON.toJSONString(data1);
JSONObject jsonObject = JSON.parseObject(tokenData);
String token = (String) jsonObject.get("token");
String str= URLEncoder.encode(ztdz,"UTF-8");
String attrUrl = "http://IP:端口/路径?token=" + token + "&addr=" + str + "&page=1&limit=2&fuzzy=true";
String attrData = HttpClientUtils.sendGet(attrUrl);
JSONObject attrJsonObject = JSON.parseObject(attrData);
if (attrJsonObject != null) {
Object attrData1 = attrJsonObject.get("data");
String AttrJsonString = JSON.toJSONString(attrData1);
JSONObject attrJsonObject1 = JSON.parseObject(AttrJsonString);
JSONArray jsonArray = attrJsonObject1.getJSONArray("addrList");
ArrayList<YwkTydzDzbqModel> ywkTydzDzbqModels = new ArrayList<>();
logger.info("jsonArray==========4" + jsonArray);
if (jsonArray != null && jsonArray.size() > 0) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
YwkTydzDzbqModel ywkTydzDzbqModel = creatList(jsonObj);
ywkTydzDzbqModels.add(ywkTydzDzbqModel);
}
}
return StandardResult.ok(ywkTydzDzbqModels);
}else {
return StandardResult.ok();
}
} catch (Exception e) {
logger.error("异常信息:", e);
return StandardResult.faild(e);
}
}
9441

被折叠的 条评论
为什么被折叠?



