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"",这这里也需要处理一下,去掉前后的双引号)
还有就是我的业务逻辑部分