关于java:Java获取第三方接口数据

7次阅读

共计 3348 个字符,预计需要花费 9 分钟才能阅读完成。

连贯工具类

/**
 * <pre>
 * 性能:httpUrlConnection 拜访近程接口工具
 * 日期:2015 年 3 月 17 日 上午 11:19:21
 * </pre>
 */
public class HttpUrlConnectionUtil {

    /**
     * <pre>
     * 办法体阐明:向近程接口发动申请,返回字符串类型后果
     * @param url 接口地址
     * @param requestMethod 申请形式
     * @param params 传递参数     重点:参数值须要用 Base64 进行转码
     * @return String 返回后果
     * </pre>
     */
    public static String httpRequestToString(String url, String requestMethod,
                                             Map<String, String> params){

        String result = null;
        try {InputStream is = httpRequestToStream(url, requestMethod, params);
            byte[] b = new byte[is.available()];
            is.read(b);
            result = new String(b);
        } catch (IOException e) {e.printStackTrace();
        }
        return result;
    }

    /**
     * <pre>
     * 办法体阐明:向近程接口发动申请,返回字节流类型后果
     * 作者:itar
     * 日期:2015 年 3 月 17 日 上午 11:20:25
     * @param url 接口地址
     * @param requestMethod 申请形式
     * @param params 传递参数     重点:参数值须要用 Base64 进行转码
     * @return InputStream 返回后果
     * </pre>
     */
    public static InputStream httpRequestToStream(String url, String requestMethod,
                                                  Map<String, String> params){

        InputStream is = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            // 将参数汇合拼接成特定格局,如 name=zhangsan&age=24
            for(String key : params.keySet()){String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){parameters = parameters.substring(0, parameters.length()-1);
            }

            // 申请形式是否为 get
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            // 申请形式是否为 post
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            if(isGet){url += "?"+ parameters;}

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();

            // 申请的参数类型 (应用 restlet 框架时,为了兼容框架,必须设置 Content-Type 为“”空)
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 设置连贯超时工夫
            conn.setConnectTimeout(50000);
            // 设置读取返回内容超时工夫
            conn.setReadTimeout(50000);
            // 设置向 HttpURLConnection 对象中输入,因为 post 形式将申请参数放在 http 注释内,因而须要设置为 ture,默认 false
            if(isPost){conn.setDoOutput(true);
            }
            // 设置从 HttpURLConnection 对象读入,默认为 true
            conn.setDoInput(true);
            // 设置是否应用缓存,post 形式不能应用缓存
            if(isPost){conn.setUseCaches(false);
            }
            // 设置申请形式,默认为 GET
            conn.setRequestMethod(requestMethod);

            //post 形式须要将传递的参数输入到 conn 对象中
            if(isPost){DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(parameters);
                dos.flush();
                dos.close();}

            // 从 HttpURLConnection 对象中读取响应的音讯
            // 执行该语句时才正式发动申请
            is = conn.getInputStream();} catch (UnsupportedEncodingException e) {e.printStackTrace();
        } catch (MalformedURLException e) {e.printStackTrace();
        } catch (IOException e) {e.printStackTrace();
        }
        return is;
    }
}

service

public interface TestService {void selectTest();

    void selectPost();}

serviceImpl 实现


@Service
public class TestServiceImpl implements TestService {

    @Override
    public void selectTest() {
        //url 对方接口
        String url="http://127.0.0.1:1313/test/get";
        System.out.println(url);
        System.out.println("----------------------");
        //map 寄存限度内容
        HashMap<String, String> map = new HashMap<>();
        String get = HttpUrlConnectionUtil.httpRequestToString(url, "GET", map);
        System.out.println(get);
        System.out.println("----------------------");
    }

    @Override
    public void selectPost() {
        //url 对方接口
        String url="http://127.0.0.1:1313/test/post/lll";
        System.out.println(url);
        System.out.println("----------------------");
        //map 寄存限度内容
        HashMap<String, String> map = new HashMap<>();
        String post = HttpUrlConnectionUtil.httpRequestToString(url, "POST", map);
        System.out.println(post);
        System.out.println("----------------------");
    }

}

管制层调用

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("test")
    public void test01(){testService.selectTest();;
    }

    @GetMapping("test/post")
    public void test02(){testService.selectPost();
    }

}

调用数据胜利

正文完
 0