zoukankan      html  css  js  c++  java
  • SpringMVC 结合HttpClient调用第三方接口实现

    使用HttpClient 依赖jar包

    1:commons-httpclient-3.0.jar

    2:commons-logging-1.1.1.jar

    3:commons-codec-1.6.jar

    本地调用测试===>>>>>>>>>>>>

    
    
    package com.me.cn.siteTrans.test;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    import com.google.gson.Gson;
    
    public class SiteTran {
    public static void main(String[] args) {
        String result = httpClientTest();
        System.out.println(result);
    }
    public static String httpClientTest(){
        HttpClient client = new HttpClient() ;
        PostMethod method = null;//post 方式   get 方式 GetMethod gMethod 
        String result = "" ;
        try {
            method = new PostMethod("http://localhost:8666/test/siteTrans/returnJson.do") ;
            method.setParameter("param","test");//设置参数
            client.executeMethod(method);
            if(method.getStatusCode() == HttpStatus.SC_OK){//响应成功
                result = method.getResponseBodyAsString();//调用返回结果
            }else{//不成功组装结果
                Map<String , Object >map = new HashMap<String , Object>();
                Gson gson = new Gson() ;
                map.put("success", false);
                result = gson.toJson(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
          method.releaseConnection();
        }
        return result ;
    }
    }
    
    
    
     

    模拟第三方接口===>>>>>>>>>>>>

    package com.cn.me.siteTrans.interface;
    import java.util.HashMap;
    import java.util.Map;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.google.gson.Gson;
    
    @Controller
    @RequestMapping("/siteTrans")
    @SuppressWarnings("all")
    public class SiteTransCtrl {
        @RequestMapping("/returnJson")
        @ResponseBody
        public Map returnJson(String param){
            Map<String , Object> map = new HashMap<String , Object>() ;
            try {            
                System.out.println(param);
                map.put("success", true) ;
                map.put("flag", true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return map;
        }
    }
  • 相关阅读:
    免费音频录制及处理软件 Audacity
    centos7设置程序开机启动方案
    tomcat开启前或者关闭前执行清理任务 servlet基础知识解决
    BigDecimal比较大小及判0处理
    File文件夹操作创建层级文件夹
    centos7设置activemq开机启动
    tomcat关闭时无法清理资源解决方案
    java数据类型和C++的对应关系 SDK开发
    centos7查询开机启动项及设置服务为开机自启动
    Entity Framework 教程
  • 原文地址:https://www.cnblogs.com/shell-blog/p/4840448.html
Copyright © 2011-2022 走看看