springMVC、httpClient调用别人提供的接口!!!(外加定时调用)
import com.ibm.db.util.AppConfig;
import com.ibm.db.util.JacksonUitl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.codehaus.jackson.JsonNode; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map; /**
*
* 调用itil工具类
*/
public class ItilRequestUtil { private String itil_url= ""; //被调用接口的url
private String itil_usernmae = ""; //用户名
private String itil_passWorld = ""; //密码
private int itil_port = ; //端口号
private String itil_protocol = "http";//协议 public ItilRequestUtil(){ } /**
* rest post 方式调用itil接口
* @param JsonParams json格式的请求参数
* @param apiUrl api接口地址
* @return
* @throws Exception
*/
public JsonNode httpRequestPost(String JsonParams,String apiUrl)throws Exception{ HttpHost targetHost = new HttpHost(itil_url, itil_port, itil_protocol); DefaultHttpClient httpclient = new DefaultHttpClient();
//设置httpclient的重试次数,默认是3次,当前是禁用掉的(如果项目量不到,这个默认即可!)
int SO_TIMEOUT = 60*1000;//设置等待数据超过时间为60秒,这里是连上别人的接口,但是迟迟不返回数据(堵塞的异常处理)
HttpParams params = new BasicHttpParams();
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,SO_TIMEOUT);
httpclient.setDefaultHttpParams(params);
//此用户名和密码上生产前需要修改为自己的账户
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(itil_usernmae, itil_passWorld)); AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
String url = itil_protocol+"://"+itil_url+":"+itil_port+apiUrl; HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(JsonParams, HTTP.UTF_8); httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("accept","application/json"); httpPost.setEntity(stringEntity); HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext); HttpEntity entity = response.getEntity(); System.out.println("StatusCode:" + response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"utf-8"));//防止乱码
String buffer = "";
StringBuffer sb = new StringBuffer();
while((buffer = reader.readLine())!=null){
sb.append(buffer);
}
reader.close();
httpPost.releaseConnection();
System.out.println("entity:" + sb.toString());
httpclient.getConnectionManager().shutdown(); JsonNode json = JacksonUitl.getObjectMapper().readTree(sb.toString());
return json; } /**
* rest get 方式调用itil接口
* @param apiUrl api接口地址,参数直接拼在地址后面
* @return json字符串格式的返回结果 其中ReturnCode为0表示请求成功
* @throws Exception
*/
public JsonNode httpRequestGet(HashMap<String, Object> content,String apiUrl)throws Exception{ HttpHost targetHost = new HttpHost(itil_url, itil_port, itil_protocol); DefaultHttpClient httpclient = new DefaultHttpClient(); //此用户名和密码上生产前需要修改为自己的账户
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(itil_usernmae, itil_passWorld)); AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
String url = itil_protocol+"://"+itil_url+":"+itil_port+apiUrl; HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("accept","application/json"); HttpResponse response = httpclient.execute(targetHost, httpGet, localcontext); HttpEntity entity = response.getEntity(); System.out.println("StatusCode:" + response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String buffer = "";
StringBuffer sb = new StringBuffer();
while((buffer = reader.readLine())!=null){
sb.append(buffer);
}
reader.close();
httpGet.releaseConnection();
System.out.println("entity:" + sb.toString());
httpclient.getConnectionManager().shutdown(); JsonNode json = JacksonUitl.getObjectMapper().readTree(sb.toString());
return json; } public static void main(String[] args) throws Exception {
/**
*其实这里不需要写这个测试的,实际项目中,直接写自己的方法调用即可!
*/ String apiUrl = "/SM/9/rest/reportoutages?view=expand";//调用方法对应的URL HashMap<String,Object> map = new LinkedHashMap<String, Object>();
map.put("sourceId","GEN00002");
map.put("assignee","0020345");
map.put("title","测试");
map.put("category","流程管理");
map.put("subcategory","itil系统");
map.put("businessArea","其他");
map.put("description","xx");
map.put("requestor","036131");
map.put("requestor","036131");
map.put("plannedEnd","2016-04-07T10:11:54+00:00");
HashMap<String,Map<String,Object>> paramsMap = new LinkedHashMap<String, Map<String, Object>>();
// paramsMap.put("GenRequest",map);
paramsMap.put("orderInfo",map);
String params = JacksonUitl.getObjectMapper().writeValueAsString(paramsMap);
//需要传入的请求参数
String pp = "{"+"\"orderInfo\": {"
+"\"sourceId\": \"GEN00002\","
+"\"assignee\": \"00203045\","
+"\"title\": \"测试:评估体系平台系统发起新情求\","
+"\"category\": \"流程管理\","
+"\"subcategory\": \"ITIL系统\","
+"\"businessArea\": \"其他\","
+"\"description\": [\"评估体系平台系统发起新情求\",\"需求详细描述\"],"
+"\"requestor\": \"036131\","
+"\"plannedEnd\": \"2015-12-11T01:00:00+08:00\"," +"}"+"}";
// map.put("name","123");
new ItilRequestUtil().httpRequestPost(pp, apiUrl);
// new ItilRequestUtil().httpRequestGet(null, apiUrl); try {
// httpRequestPost();
/* test(url_2,"{\"\":\"\"}");*/
}catch (Exception e){ }
} }
这里我还加了一个定时器,如果不需要用到定时器,则不需要以下代码。
spring自带的定时器功能(JavaSe的是Timer类)还需要在spring的配置文件中(application.xml)添加如下配置信息,配置信息可参考(http://cuisuqiang.iteye.com/blog/1320255)
<!-- 一、每个定义的任务都要在这里进行引用才能运行 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="BusinessTestTrigger" />
</list>
</property>
</bean>
<!-- 四、定义我们要运行的类,可以使用注入定制一些参数 -->
<bean id="BusinessTestTime" class="com.ibm.tools.EcpTool">
<!--<property name="para" value="Spring定时器测试V1" />-->
</bean>
<!-- 三、引用,配置要运行的方法 -->
<bean id="BusinessTestDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="BusinessTestTime" />
</property>
<property name="concurrent" value="false" />
<!--要定时执行的目标方法,我自己定义的方法为myMethod-->
<property name="targetMethod" value="myMethod" />
</bean>
<!-- 二、引用,定制调用间隔,具体时间配置的正则,请阅读readme.txt -->
<bean id="BusinessTestTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="BusinessTestDetail" />
</property>
<property name="cronExpression">
<!--每个字符分别代表秒、分、时、天、月、星期、年份
参考网址http://blog.csdn.net/xiao_wgs69/article/details/11269391
-->
<value>0/5 * * * * ?</value>
</property>
</bean>
还需要相应的jar包,maven项目之间添加,如果是普通web工程添加spring.jar,quartz-all-1.6.5.jar,quartz-1.5.2.jar,这两个jar包
<!-- https://mvnrepository.com/artifact/quartz/quartz -->
<dependency>
<groupId>quartz</groupId>
<artifactId>quartz</artifactId>
<version>1.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/opensymphony/quartz-all -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>quartz-all</artifactId>
<version>1.6.3</version>
</dependency>
已通过测试的,具体的业务逻辑,还需自己去补充!我只写了连接的通用方法,另附上Json数据转换的而工具类,因为上面用到了
public class JacksonUtil {
private static ObjectMapper objectMapper = null;
private JacksonUtil(){ } public static ObjectMapper getObjectMapper(){
if(objectMapper==null){
objectMapper = new ObjectMapper();
}
return objectMapper;
} // map转换为json
public void test01(){
Map<String,String> map = new LinkedHashMap<String,String>();
map.put("name","zhangsan");
map.put("age","1");
try{
String jsonStr = JacksonUtil.getObjectMapper().writeValueAsString(map);
//解析json字符串
JsonNode node = JacksonUtil.getObjectMapper().readTree(jsonStr);
System.out.println(jsonStr);
System.out.println("name="+node.get("name").asText());
System.out.println("name="+node.get("name"));
}catch (Exception e){
e.printStackTrace();
}
} // 解析json格式字符串
public void test02(){
String json = "{data:{\"birth_day\":7,\"birth_month\":6},\"errcode\":0,\"msg\":\"ok\",\"rest\":0}";
try {
JsonNode node = JacksonUtil.getObjectMapper().readTree(json);
JsonNode data = node.path("data"); JsonNode birth_day = data.path("birth_day");
System.out.println(birth_day.asInt()); JsonNode birth_month = data.path("birth_month");
System.out.println(birth_month.asInt()); JsonNode msg = node.path("msg");
System.out.println(msg.getTextValue()); } catch (IOException e) {
e.printStackTrace();
}
} //json直接提取值
public static void MyTest05(){
String str = "{\"data\":{\"hashnext\":0,\"info\":[{\"id\":\"939399393\",\"timestamp\":\"22242244\"},{\"id\":\"939399393\",\"timestamp\":\"22242244\"},{\"id\":\"939399393\",\"timestamp\":\"22242244\"}],\"errcode\":0,\"msg\":\"ok\",\"rest\":0}}"; ObjectMapper mapper = new ObjectMapper();
try {
JsonNode root = mapper.readTree(str);
//提取data
JsonNode data = root.path("data");
//提取info
JsonNode info = root.path("info");
System.out.println(info.size()); JsonNode item = info.get(0);
System.out.println(item.get("id"));
System.out.println(item.get("timestamp"));
//得到info的第二个值
item = info.get(1);
System.out.println(item.get("id"));
System.out.println(item.get("timestamp")); if(info.isArray()){
for(JsonNode jsonNode:info){
System.out.println(jsonNode);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//创建一个json,并像该json添加内容
public static void MyTest07(){
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode(); objectNode.put("nodekey1",1);
objectNode.put("nodekey2",2); System.out.println(objectNode.toString()); ObjectNode root = mapper.createObjectNode(); ObjectNode node1 = mapper.createObjectNode();
node1.put("nodekey1", 1);
node1.put("nodekey2", 2); root.put("child",node1); ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.add(node1);
arrayNode.add(1);
root.put("arraynode",arrayNode); try {
System.out.println(mapper.writeValueAsString(root));
} catch (IOException e) {
e.printStackTrace();
} } // 创建一个arrayNode
public static void MyTest08(){
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode(); int i = 0;
// 在array内创建3组存入array for(i=0;i<3;i++){
ObjectNode node = mapper.createObjectNode();
node.put("nodeA",i);
node.put("nodeB",i);
node.put("nodeC",i); arrayNode.add(node);
} ObjectNode root = mapper.createObjectNode();
root.put("total",i);
root.put("rows",arrayNode); try {
System.out.println(mapper.writeValueAsString(root));
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args){
new JacksonUtil().test01();
new JacksonUtil().test02();
new JacksonUtil().MyTest05();
new JacksonUtil().MyTest07();
new JacksonUtil().MyTest08();
}
}
注:因为别人返回给我的是字符串类型的Json数据,我用String去接收的时候就多了另个引号,如本来是"hello",变成了""hello"",这这里也需要处理一下,去掉前后的双引号)
还有就是我的业务逻辑部分
springMVC、httpClient调用别人提供的接口!!!(外加定时调用)的更多相关文章
- springMVC、https、GET调用别人提供的接口!!!
import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatu ...
- 调用别人提供的WebService
在开发过程中,许多时候需要使用到别人提供的WebService接口,使用其中的方法. 在调用别人提供的接口时,会得到接口使用的文档,其中包括接口的网络地址及方法作用等. 找到WebService的ws ...
- 如何调用别人提供的webservice接口
当我们拿到一个接口的时候,先别急着去调用它,我们得先测试这个接口是否正确,是否能调用成功,以及返回的数据是否是我们需要的类型等等.这时候我们需要一个工具,比如SoapUI.(最好用绿色免安装版的.)然 ...
- 通用的调用WebService的两种方法。(调用别人提供的wsdl)(转)
转载自:http://blog.sina.com.cn/s/blog_65933e020101incz.html1.调用WebService的Client端采用jax-ws调用WebService:流 ...
- 如何调用别人提供的API?
1:一般使用聚合数据提供的API: 百度聚合数据,进入: 2:一般是有用户名的直接登录,没有用户名的先进行注册.在搜索框中输入你想查找的API方面的关键字:例如:有关健康的 点开任意一个,你将会看到: ...
- jquery怎么实现跨域的访问呢?与别人提供的接口连接
下面这个例子你可以参考下 <script> $.ajax({ async:false, url: 'http://www.mysite.com/demo.do', // 跨域URL ty ...
- java 调用wsdl的webservice接口 两种调用方式
关于wsdl接口对于我来说是比较头疼的 基本没搞过.一脸懵 就在网上搜 看着写的都很好到我这就不好使了,非常蓝瘦.谨以此随笔纪念我这半个月踩过的坑... 背景:短短两周除了普通开发外我就接到了两个we ...
- Apache cxf暴露接口以及客户端调用之WebService初步理解
在我们真实的项目中,经常会调用别人提供给我们的接口,或者在自己的团队中, restful风格的前后端分离也经常会提供一个后端接口暴露出去供app,或者.net/C/C++程序员去调用,此时就需要使用到 ...
- Spring Boot提供RESTful接口时的错误处理实践
使用Spring Boot开发微服务的过程中,我们会使用别人提供的接口,也会设计接口给别人使用,这时候微服务应用之间的协作就需要有一定的规范. 基于rpc协议,我们一般有两种思路:(1)提供服务的应用 ...
随机推荐
- https://zeroc.com/index.html
https://zeroc.com/index.html http://blog.shutupandcode.net/?p=1085
- Python简单源码解析
主要为一些简单的源代码的解析以及一些方法的理解. 说明:这些文件都不是我写的,详情可参考Github上的内容. 批量修改文件类型 def batch_rename(work_dir, old_ext, ...
- runtime的黑魔法
要说明runtime,首先要明白objc这门语言,是基于C的封装.真是因为runtime,objc才有了面对对象的特性. 也就说,所有objc的语言,在运行时都会转换成C. 也是基于这样的特性,run ...
- 进度条ProgressDialog
1.效果图 public void click(View view) { final ProgressDialog pdDialog = new ProgressDialog(this); //设置标 ...
- Linq查询表达式
目录 1. 概述 2. from子句 3. where子句 4. select子句 5. group子句 6. into子句 7. 排序子句 8. let子句 9. join子句 10. 小结 1. ...
- s:select下拉框validation验证
S:select下拉框验证: <td colspan="5"> <s:select name="vo.typeVO.corp" list=&q ...
- bootstrap-datetimepicker 日期控件的开始日期
今天做日期控件,需求要求设置一个时间范围限制,选择从今天开始的日期才可以选择,今天以前都不可以选择 主要体现在bootstrap-datetimepicker控件下面的2个日期参数 weekStart ...
- 使用vs2008搭建php扩展环境
所需要的工具或者文件: 1.php源码,去官网下载即可.http://windows.php.net/download 2.php-sdk:php 开发工具包 3.deps类库 4.Cygwin:wi ...
- T-SQL函数总结
T-SQL函数的类别和描述. 函数类别 作用 聚合函数 执行的操作是将多个值合并为一个值.例如COUNT.SUM.MIN 和 MAX. 配置函数 是一种标量函数,可返回有关配置设置的信息. 转换函数 ...
- 【Java EE 学习 15】【自定义数据库连接池之动态代理的使用】
一.动态代理的作用 使用动态代理可以拦截一个对象某个方法的执行,并执行自定义的方法,其本质是反射 优点:灵活 缺点:由于其本质是反射,所以执行速度相对要慢一些 二.数据库连接池设计思想 1.为什么要使 ...