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"",這這里也需要處理一下,去掉前后的雙引號)

還有就是我的業務邏輯部分


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM