在Java中提供HTTP接口通常有以下几种方式:
1. 使用Java内置的`HttpURLConnection`类:
```java
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版本):
```java
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库:
```java
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`:
```java
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框架集成得更好。
请根据你的具体情况选择合适的方法,并注意处理异常和关闭资源