java如何写一个http接口_java调用接口

java如何写一个http接口_java调用接口在 Java 中提供 HTTP 接口通常有以下几种方式 1 使用 Java 内置的 HttpURLConne 类 javaimport java io BufferedRead import java io InputStreamR import java net HttpURLConne import java net URL public class

在Java中提供HTTP接口通常有以下几种方式:

1. 使用Java内置的`HttpURLConnection`类:

 import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionClientUtil { public static String doGet(String httpUrl) throws IOException { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; StringBuffer response = new StringBuffer(); try { URL url = new URL(httpUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } } } finally { if (connection != null) { connection.disconnect(); } } return response.toString(); } } 

2. 使用Apache HttpClient库(推荐使用最新版本的4.5版本):

 import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; public class HttpClientExample { public static void main(String[] args) { String resultUrl = "http://localhost:9080/projectName/servletName"; HttpPost httpPost = new HttpPost(resultUrl); String param = "taskid=123"; StringEntity s = new StringEntity(param); httpPost.setEntity(s); // 执行请求并处理响应 } } 

3. 使用OkHttp库:

 import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpExample { public static void doGet(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .get() .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } } } 

4. 使用Spring框架的`RestTemplate`:

 import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api"; String result = restTemplate.getForObject(url, String.class); System.out.println(result); } } 

选择哪种方式取决于你的项目需求以及个人偏好。如果你使用的是普通的Java项目,推荐使用OkHttp,因为它简单且高效。如果你使用的是Spring项目,推荐使用`RestTemplate`,因为它与Spring框架集成得更好。

请根据你的具体情况选择合适的方法,并注意处理异常和关闭资源

编程小号
上一篇 2025-05-22 15:42
下一篇 2025-05-31 20:14

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/64541.html