java调用第三方接口获取(保存)数据

后台java获取第三方接口数据:

	import org.springframework.web.client.RestTemplate;
	import org.codehaus.jackson.JsonNode;
	import org.codehaus.jackson.type.TypeReference;
	import org.codehaus.jackson.map.ObjectMapper;
	//ajax调用后台:
	$.ajax({
	type:"get",
			dataType:"json",
			url:"ztreeInfoController.do?geZtreeInfo&userId="+"123"+"&userName="+"张山",
			success:function(result){
					//dosomething
			}
	})
	private RestTemplate template = new RestTemplate();
	//获取数据
	@ResponseBody
	@RequestMapping(params = "geZtreeInfo")
	public List> getDepertmentData(String userId, String userName)
			throws Exception, IOException {
		List> resultList = new ArrayList>();
		//第三方接口url 
		String url = "http://192.168.233.143:8080/api/getZtreeInfo?userId=" + userId+ "&userName="+ userName;
		String obj = template.getForObject(url, String.class);
		ObjectMapper objectMapper = new ObjectMapper();
		JsonNode jsonNode = objectMapper.readTree(obj);
		//默认传json格式 ,根据格式读取对应数据
		resultList = objectMapper.readValue(jsonNode.get("res_body").get("data_list"),
				new TypeReference>>() {
				});//将获取到的数据转换成List>类型
		return resultList;
	}
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
//ajax调用后台:
$.ajax({
			type:"post",
			dataType:"json",
			data:{"id":id,"name":name},
			traditional:true,//传递tableData数组使用
			url:"ztreeInfoController.do?postData",
			success:function(result){
				if(result && result=="0"){
					alert("保存成功");
				}
			}
		});
//提交数据
    @ResponseBody
	@RequestMapping(params = "postData", method = RequestMethod.POST)
	public String postTableData(String id, String name) {
		//往UserEntity保存好数据
		List list = new ArrayList();
		//调用第三方接口
		String url = "http://192.168.233.143:8080/api/postInfo";
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		String json = JSONArray.fromObject(list).toString();
		HttpEntity entity= new HttpEntity(json, headers);
		String obj = template.postForObject(url, entity, String.class);
		ObjectMapper objectMapper = new ObjectMapper();
		JsonNode jsonNode = objectMapper.readTree(obj);
	    //接口保存成功后会返回成功提示信息
		String code = objectMapper.readValue(jsonNode.get("res_code"), new TypeReference() {});
		if ("200".equals(code)) {
			return "0";// 成功
		} else {
			return "1";//失败
		}
		return "1";
	}

你可能感兴趣的:(java)