get请求和post请求获取jsonp数据

package com.trt.framework.ixm.api;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public abstract class BaseApi {

    @Autowired
    public RestTemplate restTemplate;

    /** get请求jsonp数据 公共方法
     *
     * @param url
     * @return
     */
    public String formatJsonp2Json(String url) {
        try {

            String jsonpStr = restTemplate.getForEntity(url, String.class).getBody();
            if(jsonpStr.contains("(")&&jsonpStr.endsWith(")")){
                String jsonStr = jsonpStr.substring(jsonpStr.indexOf("(") + 1, jsonpStr.lastIndexOf(")"));
                return jsonStr;
            }

            return "{\"result\":false,\"msg\":"+jsonpStr+"}";
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"result\":false,\"msg\":"+e.getMessage()+"}";
        }
    }



    /** post请求公共方法
     *
     * @param url
     * @param data
     * @return
     */
    public String postRest(String url, Map data) {
        try {
            //设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);

            //构造请求
            HttpEntity requ = new HttpEntity(data, httpHeaders);

            return restTemplate.postForEntity(url, requ, String.class).getBody();

        } catch (Exception e) {
            e.printStackTrace();
            return "{\"result\":false,\"msg\":"+e.getMessage()+"}";
        }
    }

}

你可能感兴趣的:(java)