码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC 结合HttpClient调用第三方接口实现

时间:2015-09-26 11:52:21      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

使用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 SiteTranCtrl {
public static void main(String[] args) {
    String result = httpClientTest();
    System.out.println(result);
}
public static String httpClientTest(){
    HttpClient client = new HttpClient() ;
    String result = "" ;
    try {
        PostMethod method = new PostMethod("http://localhost:8666/test/siteTrans/returnJson.do?param={test: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();
    }
    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 SiteTrans {
    @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;
    }
}

 

SpringMVC 结合HttpClient调用第三方接口实现

标签:

原文地址:http://www.cnblogs.com/shell-blog/p/4840448.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!