java基础-java中http请求调用外部接口几种情况

愿历尽千帆,归来仍是少年

Java中,常用四种方式调用http请求外部接口

第一种:使用原生的Java网络编程(HttpURLConnection) -  不推荐

复制代码
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    StringBuilder response = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    reader.close();
    System.out.println(response.toString());
} else {
    System.out.println("HTTP Request Failed with error code: " + responseCode);
}
connection.disconnect();
复制代码

使用原生的Java网络编程:通过使用java.net.HttpURLConnection类,可以创建HTTP连接并发送请求,然后手动处理响应。这种方式需要手动构建请求参数、设置请求头、处理响应数据等步骤。

第二种:使用第三方库(Apache HttpClient)

复制代码
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity);
    System.out.println(result);
} catch (IOException e) {
    e.printStackTrace();
}
复制代码

OKHttp

复制代码
try {
         log.info("日志打印 By File start!");
         OkHttpClient client = new OkHttpClient().newBuilder()
                 .build();
         okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
         RequestBody body = RequestBody.create(mediaType, param);
         Request request = new Request.Builder()
                 .url(URL)
                 .method("POST", body)
                 .addHeader("Content-Type", "application/json")
                 .build();
         Response response = client.newCall(request).execute();
         JSONObject resultJson = JSONObject.parseObject(response.body().string());
         log.info("日志打印 By File end! 返回数据:" + resultJson.toJSONString());
      } catch (Exception e) {
         log.info("日志打印异常! 异常信息:" + e);
      }
复制代码

使用第三方库:Java有许多流行的HTTP客户端库,例如Apache HttpClient和OkHttp等。这些库提供了更高级的API,使得发送和处理HTTP请求更加方便。它们通常提供了更简洁的接口,可以处理诸如请求构建、响应解析、错误处理等方面的细节

第三种:使用框架(Spring RestTemplate)

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://example.com/api", String.class);
System.out.println(response);

使用框架:Java框架如Spring提供了集成HTTP请求的功能。例如,Spring的RestTemplate类提供了发送HTTP请求的简便方法,可以轻松处理常见的GET、POST等请求。另外,Spring WebFlux提供的WebClient类也可以用来进行非阻塞的HTTP请求。

第四种:使用第三方工具类(Apache HttpComponents)

复制代码
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");

try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity);
    System.out.println(result);
} catch (IOException e) {
    e.printStackTrace();
}
复制代码

使用第三方工具类:除了上述库和框架之外,还有一些第三方的工具类可用于简化HTTP请求的调用。例如,Apache的HttpComponents库提供了高级别的HTTP客户端,如CloseableHttpClient,可以处理连接管理、状态保持、请求重试等。

posted @   归来仍是少年-youg  阅读(2284)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示