java以post方式調用接口

一般现在系统之间最常用的有四种接口机制;

1.JsonP;

2.HttpClient;

3.实木复合地板;

4.WebService;

解释:

JSONP

1)  不能脱离 js ,基于js ,应用面就在Js

2)  不是真正返回 JSON 串,而是返回一个函数包装起来的JSON

3)  函数名通过获得请求参数提交,可以定义不同的函数名称

4)jQuery (不定义函数名,内部给了一个随机值),springmvc jsonp 支持

5)jsonp 解决js 的同源策略,跨域


HttpClient的

1)  从前台控制器响应用户请求,将用户请求转发到前台服务

2)  前台服务注入httpClientService 对象,然后调用doGet url,encode ),内部发起一个http 请求(安全,速度快)

3)  请求访问后台控制器控制器去调用服务服务调用数据库,然后获取数据,封装到java 对象,服务返回给后台的控制器

4)controller java 对象转成成json httpClient 调用返回json

5)  在前台服务中,将json ObjectMapper 转换成java 对象,返回给前台控制器

6)  前台控制器Java的对象放入模型

7)jsp 页面从模型中获取相应的数据

实木复合地板

1)压缩的json

2)二进制json


WebService慢慢的要被淘汰,所以不讲

直接上代码

public static StringBuffer getItemInfo(String url,String param)throws IOException {

网址wsUrl =新网址(url);
HttpURLConnection conn =(HttpURLConnection)wsUrl.openConnection();
conn.setDoOutput(真);
conn.setDoInput(真);
conn.setUseCaches(假);
conn.setRequestMethod( “POST”);


//“conn.setRequestProperty(”Content-type“,”application / x-www-form-urlencoded“);
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.connect();


DataOutputStream out = new DataOutputStream(conn.getOutputStream());
JSONObject args = new JSONObject();
//args.put("UpdateTime“,”2018-06-06 15:00:00“);
args.put(“UpdateTime”,param);
out.writeBytes(args.toString());
了out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
字符串行;
StringBuffer sb = new StringBuffer();
while((lines = reader.readLine())!= null){
lines = new String(lines.getBytes(),“utf-8”);
sb.append(线);
}
reader.close();
的System.out.println( “---------------------------”);
的System.out.println(SB);
的System.out.println( “---------------------------”);
//关闭连接
conn.disconnect();
返回某人;

}

以邮寄方式调用接口

public static <T> List <T> stringBufferChangesList(List <T> list,StringBuffer param){
if(!list.isEmpty()|| list.size()!= 0){
return null;
} if(param == null ||“”。equals(param)){ return null;



}

尝试{

        String params = param.toString();
//允许出现转义字符与
特殊字符_mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS,true);
list = _mapper.readValue(params,List.class);
} catch(Exception e){
logger.info(e.getMessage());
}
返回列表;

}

将JSON串转换成集合

public static void main(String [] args){
String url =“http://192.*****:8070 / ******** / getItemInfo”;
String param =“2018-06-06 15:00:00”;
StringBuffer itemInfo;
尝试{
itemInfo = GetERPInterfaceByWebservice.getItemInfo(url,param);
List <ItemInfo> list = new ArrayList <ItemInfo>(); GetERPInterfaceByWebservice.changes(list,itemInfo); } catch(IOException e){ // TODO自动生成的catch块e.printStackTrace(); } }







猜你喜欢

转载自blog.csdn.net/qq_25879695/article/details/80784371
今日推荐