java代码如何调用第三方接口呢?
下文笔者讲述java代码调用第三方接口的方法及示例分享,如下所示
Java代码调用第三方接口,可使用以下方法 HttpURLConnection 或 HttpClient来发送HTTP请求到第三方接口的URL 此方法请求时,可设置头部信息及请求体参数例:java代码调用第三方接口的示例
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class CallThirdPartyApi { public static void main(String[] args) { try { URL url = new URL("http://java265.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。